<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>医院管理系统 - 管理员首页</title>
    <!-- 指定站点图标，避免浏览器请求 /favicon.ico 404 -->
    <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='10' fill='%23667eea'/%3E%3Ctext x='50%' y='55%' text-anchor='middle' font-size='36' fill='white' font-family='Arial'%3EA%3C/text%3E%3C/svg%3E">
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .sidebar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: white;
        }
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            border-radius: 8px;
            margin: 2px 0;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover {
            background: rgba(255, 255, 255, 0.1);
            color: white;
        }
        .sidebar .nav-link.active {
            background: rgba(255, 255, 255, 0.2);
            color: white;
        }
        .main-content {
            padding: 2rem;
        }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            transition: transform 0.3s;
        }
        .card:hover {
            transform: translateY(-5px);
        }
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .stat-card .card-body {
            padding: 2rem;
        }
        .stat-number {
            font-size: 2.5rem;
            font-weight: bold;
        }
        .table {
            border-radius: 10px;
            overflow: hidden;
        }
        .btn-action {
            padding: 5px 10px;
            margin: 2px;
            border-radius: 5px;
        }
        .modal-content {
            border-radius: 15px;
        }
        .form-control, .form-select {
            border-radius: 8px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-3 col-lg-2 sidebar">
                <div class="p-3">
                    <h4 class="text-center mb-4">
                        <i class="fas fa-hospital me-2"></i>管理系统
                    </h4>
                    <nav class="nav flex-column">
                        <a class="nav-link active" href="#" onclick="showDashboard()">
                            <i class="fas fa-tachometer-alt me-2"></i>仪表盘
                        </a>
                        <a class="nav-link" href="#" onclick="showDepartmentManagement()">
                            <i class="fas fa-building me-2"></i>科室管理
                        </a>
                        <a class="nav-link" href="#" onclick="showDoctorManagement()">
                            <i class="fas fa-user-md me-2"></i>医生管理
                        </a>
                        <a class="nav-link" href="#" onclick="showScheduleManagement()">
                            <i class="fas fa-calendar-alt me-2"></i>排班管理
                        </a>
                        <a class="nav-link" href="#" onclick="showReservationManagement()">
                            <i class="fas fa-calendar-check me-2"></i>预约管理
                        </a>
                        <a class="nav-link" href="#" onclick="showMedicalRecordManagement()">
                            <i class="fas fa-file-medical me-2"></i>病历管理
                        </a>
                        <a class="nav-link" href="#" onclick="showAdmissionApproval()">
                            <i class="fas fa-user-check me-2"></i>住院审核
                        </a>
                        <a class="nav-link" href="#" onclick="showDrugPurchaseApproval()">
                            <i class="fas fa-pills me-2"></i>购药审批
                        </a>
                        <a class="nav-link" href="#" onclick="showOrderManagement()">
                            <i class="fas fa-receipt me-2"></i>订单管理
                        </a>
                        <hr>
                        <a class="nav-link" href="#" onclick="logout()">
                            <i class="fas fa-sign-out-alt me-2"></i>退出登录
                        </a>
                    </nav>
                </div>
            </div>

            <!-- 主内容区 -->
            <div class="col-md-9 col-lg-10 main-content">
                <!-- 仪表盘 -->
                <div id="dashboard" class="content-section">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-tachometer-alt me-2"></i>管理员仪表盘</h2>
                        <span class="text-muted">欢迎回来，管理员</span>
                    </div>

                    <!-- 统计卡片 -->
                    <div class="row mb-4">
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-building fa-2x mb-2"></i>
                                    <div class="stat-number" id="departmentCount">-</div>
                                    <div>科室总数</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-user-md fa-2x mb-2"></i>
                                    <div class="stat-number" id="doctorCount">-</div>
                                    <div>医生总数</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-user fa-2x mb-2"></i>
                                    <div class="stat-number" id="patientCount">-</div>
                                    <div>患者总数</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-calendar-check fa-2x mb-2"></i>
                                    <div class="stat-number" id="reservationCount">-</div>
                                    <div>今日预约</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 最近活动 -->
                    <div class="row">
                        <div class="col-md-8">
                            <div class="card">
                                <div class="card-header">
                                    <h5><i class="fas fa-chart-line me-2"></i>系统概览</h5>
                                </div>
                                <div class="card-body">
                                    <p class="text-muted">医院管理系统运行正常，所有功能模块均可正常使用。</p>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <h6>系统状态</h6>
                                            <ul class="list-unstyled">
                                                <li><i class="fas fa-check-circle text-success me-2"></i>数据库连接正常</li>
                                                <li><i class="fas fa-check-circle text-success me-2"></i>用户认证系统正常</li>
                                                <li><i class="fas fa-check-circle text-success me-2"></i>预约系统正常</li>
                                            </ul>
                                        </div>
                                        <div class="col-md-6">
                                            <h6>快速操作</h6>
                                            <div class="d-grid gap-2">
                                                <button class="btn btn-outline-primary" onclick="showDepartmentManagement()">
                                                    <i class="fas fa-plus me-2"></i>添加科室
                                                </button>
                                                <button class="btn btn-outline-success" onclick="showDoctorManagement()">
                                                    <i class="fas fa-user-plus me-2"></i>添加医生
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">
                                    <h5><i class="fas fa-bell me-2"></i>系统通知</h5>
                                </div>
                                <div class="card-body">
                                    <div class="alert alert-info">
                                        <small>系统已更新到最新版本</small>
                                    </div>
                                    <div class="alert alert-warning">
                                        <small>请定期备份数据库</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 科室管理 -->
                <div id="departmentManagement" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-building me-2"></i>科室管理</h2>
                        <button class="btn btn-primary" onclick="showAddDepartmentModal()">
                            <i class="fas fa-plus me-2"></i>添加科室
                        </button>
                    </div>

                    <!-- 搜索和筛选 -->
                    <div class="card mb-3">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                                        <input type="text" class="form-control" id="departmentSearch" placeholder="搜索科室名称..." onkeyup="filterDepartments()">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <select class="form-select" id="departmentLevelFilter" onchange="filterDepartments()">
                                        <option value="">所有楼层</option>
                                        <option value="1楼">1楼</option>
                                        <option value="2楼">2楼</option>
                                        <option value="3楼">3楼</option>
                                        <option value="4楼">4楼</option>
                                        <option value="5楼">5楼</option>
                                        <option value="6楼">6楼</option>
                                        <option value="7楼">7楼</option>
                                        <option value="8楼">8楼</option>
                                        <option value="9楼">9楼</option>
                                        <option value="10楼">10楼</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <button class="btn btn-outline-secondary" onclick="resetDepartmentFilter()">
                                        <i class="fas fa-undo me-1"></i>重置筛选
                                    </button>
                                </div>
                                <div class="col-md-2">
                                    <button class="btn btn-outline-primary" onclick="loadDepartments()">
                                        <i class="fas fa-sync-alt me-1"></i>刷新
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <!-- <th>科室ID</th> -->
                                            <th>科室名称</th>
                                            <th>所在楼层</th>
                                            <th>科室电话</th>
                                            <th>创建时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="departmentTableBody">
                                        <!-- 动态加载数据 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 医生管理 -->
                <div id="doctorManagement" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-user-md me-2"></i>医生管理</h2>
                        <div class="btn-group">
                            <button class="btn btn-primary" onclick="showAddDoctorModal()">
                                <i class="fas fa-plus me-2"></i>添加医生
                            </button>
                            <button class="btn btn-outline-success" onclick="refreshDoctorData()" title="刷新数据">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="btn btn-outline-info" onclick="showDoctorStatistics()" title="查看统计">
                                <i class="fas fa-chart-bar"></i>
                            </button>
                            <button class="btn btn-outline-secondary" onclick="exportDoctorData()" title="导出数据">
                                <i class="fas fa-download"></i>
                            </button>
                        </div>
                    </div>

                    <!-- 搜索和筛选 -->
                    <div class="card mb-3">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                                        <input type="text" class="form-control" id="doctorSearch" placeholder="搜索医生姓名..." onkeyup="filterDoctors()">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <select class="form-select" id="doctorDepartmentFilter" onchange="filterDoctors()">
                                        <option value="">所有科室</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <select class="form-select" id="doctorStateFilter" onchange="filterDoctors()">
                                        <option value="">所有状态</option>
                                        <option value="1">在职</option>
                                        <option value="0">离职</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <button class="btn btn-outline-secondary" onclick="resetDoctorFilter()">
                                        <i class="fas fa-undo me-1"></i>重置筛选
                                    </button>
                                    <button class="btn btn-outline-primary" onclick="loadDoctors()">
                                        <i class="fas fa-sync-alt me-1"></i>刷新
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <!-- <th>医生ID</th> -->
                                            <th>姓名</th>
                                            <th>性别</th>
                                            <th>年龄</th>
                                            <th>职称</th>
                                            <th>专业</th>
                                            <th>所属科室</th>
                                            <th>状态</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="doctorTableBody">
                                        <!-- 动态加载数据 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 排班管理 -->
                <div id="scheduleManagement" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-calendar-alt me-2"></i>排班管理</h2>
                        <div class="btn-group">
                            <button class="btn btn-primary" onclick="showAddScheduleModal()">
                                <i class="fas fa-plus me-2"></i>添加排班
                            </button>
                            <button class="btn btn-outline-success" onclick="refreshScheduleData()" title="刷新数据">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="btn btn-outline-primary" onclick="seedFutureSchedules()" title="添加示例排班（未来可预约）">
                                <i class="fas fa-magic"></i>
                            </button>
                        </div>
                    </div>

                    <!-- 搜索和筛选 -->
                    <div class="card mb-3">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                                        <input type="text" class="form-control" id="scheduleSearch" placeholder="搜索医生姓名..." onkeyup="filterSchedules()">
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <select class="form-select" id="scheduleDepartmentFilter" onchange="filterSchedules()">
                                        <option value="">所有科室</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <input type="date" class="form-control" id="scheduleDateFilter" onchange="filterSchedules()" placeholder="选择日期">
                                </div>
                                <div class="col-md-2">
                                    <select class="form-select" id="scheduleTimeFilter" onchange="filterSchedules()">
                                        <option value="">所有时段</option>
                                        <option value="08:30-09:00">08:30-09:00</option>
                                        <option value="09:00-09:30">09:00-09:30</option>
                                        <option value="09:30-10:00">09:30-10:00</option>
                                        <option value="10:00-10:30">10:00-10:30</option>
                                        <option value="14:00-14:30">14:00-14:30</option>
                                        <option value="14:30-15:00">14:30-15:00</option>
                                        <option value="15:00-15:30">15:00-15:30</option>
                                        <option value="15:30-16:00">15:30-16:00</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <button class="btn btn-outline-secondary" onclick="resetScheduleFilter()">
                                        <i class="fas fa-undo me-1"></i>重置筛选
                                    </button>
                                    <button class="btn btn-outline-primary" onclick="loadSchedules()">
                                        <i class="fas fa-sync-alt me-1"></i>刷新
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>排班ID</th>
                                            <th>医生</th>
                                            <th>科室</th>
                                            <th>日期</th>
                                            <th>时段</th>
                                            <th>剩余号源</th>
                                            <th>已预约</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="scheduleTableBody">
                                        <!-- 动态加载数据 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 预约管理 -->
                <div id="reservationManagement" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-calendar-check me-2"></i>预约管理</h2>
                        <div class="btn-group">
                            <button class="btn btn-outline-success" onclick="refreshReservationData()" title="刷新数据">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="btn btn-outline-info" onclick="showReservationStatistics()" title="查看统计">
                                <i class="fas fa-chart-bar"></i>
                            </button>
                            <button class="btn btn-outline-secondary" onclick="exportReservationData()" title="导出数据">
                                <i class="fas fa-download"></i>
                            </button>
                        </div>
                    </div>

                    <!-- 搜索和筛选 -->
                    <div class="card mb-3">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                                        <input type="text" class="form-control" id="reservationSearch" placeholder="搜索患者姓名..." onkeyup="filterReservations()">
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <select class="form-select" id="reservationDoctorFilter" onchange="filterReservations()">
                                        <option value="">所有医生</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <select class="form-select" id="reservationDepartmentFilter" onchange="filterReservations()">
                                        <option value="">所有科室</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <select class="form-select" id="reservationStateFilter" onchange="filterReservations()">
                                        <option value="">所有状态</option>
                                        <option value="0">待就诊</option>
                                        <option value="1">已就诊</option>
                                        <option value="2">已取消</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <button class="btn btn-outline-secondary" onclick="resetReservationFilter()">
                                        <i class="fas fa-undo me-1"></i>重置筛选
                                    </button>
                                    <button class="btn btn-outline-primary" onclick="loadReservations()">
                                        <i class="fas fa-sync-alt me-1"></i>刷新
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>预约ID</th>
                                            <th>患者</th>
                                            <th>医生</th>
                                            <th>科室</th>
                                            <th>预约时间</th>
                                            <th>预约号</th>
                                            <th>状态</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="reservationTableBody">
                                        <!-- 动态加载数据 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 购药审批 -->
                <div id="drugPurchaseApproval" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-pills me-2"></i>购药审批</h2>
                        <div class="d-flex gap-2">
                            <button class="btn btn-outline-primary" onclick="loadDrugPurchasePending()">
                                <i class="fas fa-sync-alt me-2"></i>刷新
                            </button>
                        </div>
                    </div>
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-list me-2"></i>待审批清单</h5>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>申请编号</th>
                                            <th>患者</th>
                                            <th>申请时间</th>
                                            <th>总金额</th>
                                            <th>明细</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="purchaseApprovalTable">
                                        <tr><td colspan="6" class="text-center text-muted">暂无待审批申请</td></tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 病历管理 -->
                <div id="medicalRecordManagement" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-file-medical me-2"></i>病历管理</h2>
                        <div class="btn-group">
                            <button class="btn btn-outline-success" onclick="refreshMedicalRecordData()" title="刷新数据">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="btn btn-outline-info" onclick="showMedicalRecordStatistics()" title="查看统计">
                                <i class="fas fa-chart-bar"></i>
                            </button>
                            <button class="btn btn-outline-secondary" onclick="exportMedicalRecordData()" title="导出数据">
                                <i class="fas fa-download"></i>
                            </button>
                        </div>
                    </div>

                    <!-- 搜索和筛选 -->
                    <div class="card mb-3">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                                        <input type="text" class="form-control" id="medicalRecordSearch" placeholder="搜索患者姓名..." onkeyup="filterMedicalRecords()">
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <select class="form-select" id="medicalRecordDoctorFilter" onchange="filterMedicalRecords()">
                                        <option value="">所有医生</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <select class="form-select" id="medicalRecordDepartmentFilter" onchange="filterMedicalRecords()">
                                        <option value="">所有科室</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <input type="date" class="form-control" id="medicalRecordDateFilter" onchange="filterMedicalRecords()" placeholder="选择日期">
                                </div>
                                <div class="col-md-3">
                                    <button class="btn btn-outline-secondary" onclick="resetMedicalRecordFilter()">
                                        <i class="fas fa-undo me-1"></i>重置筛选
                                    </button>
                                    <button class="btn btn-outline-primary" onclick="loadMedicalRecords()">
                                        <i class="fas fa-sync-alt me-1"></i>刷新
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>病历ID</th>
                                            <th>预约ID</th>
                                            <th>患者</th>
                                            <th>医生</th>
                                            <th>科室</th>
                                            <th>诊断结果</th>
                                            <th>创建时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="medicalRecordTableBody">
                                        <!-- 动态加载数据 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 订单管理 -->
                <div id="orderManagement" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-receipt me-2"></i>订单管理</h2>
                        <div class="d-flex gap-2">
                            <select class="form-select" id="orderStatusFilter" style="width:auto;">
                                <option value="">全部</option>
                                <option value="0">未支付</option>
                                <option value="1">已支付</option>
                                <option value="2">已退款</option>
                            </select>
                            <button class="btn btn-outline-primary" onclick="loadAllOrders()">
                                <i class="fas fa-sync-alt me-2"></i>刷新
                            </button>
                        </div>
                    </div>
                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>订单号</th>
                                            <th>患者ID</th>
                                            <th>项目</th>
                                            <th>金额</th>
                                            <th>支付状态</th>
                                            <th>来源</th>
                                            <th>创建时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="ordersTableBody">
                                        <tr><td colspan="8" class="text-center text-muted">暂无订单</td></tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 住院审核 -->
                <div id="admissionApproval" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-user-check me-2"></i>住院审核</h2>
                        <div class="btn-group">
                            <button class="btn btn-outline-success" onclick="refreshAdmissionData()" title="刷新数据">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="btn btn-outline-info" onclick="showAdmissionStatistics()" title="查看统计">
                                <i class="fas fa-chart-bar"></i>
                            </button>
                        </div>
                    </div>

                    <!-- 搜索和筛选 -->
                    <div class="card mb-3">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                                        <input type="text" class="form-control" id="admissionSearch" placeholder="搜索患者姓名..." onkeyup="filterAdmissions()">
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <select class="form-select" id="admissionStatusFilter" onchange="filterAdmissions()">
                                        <option value="">所有状态</option>
                                        <option value="0">待审核</option>
                                        <option value="1">已通过</option>
                                        <option value="2">已拒绝</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <select class="form-select" id="admissionDepartmentFilter" onchange="filterAdmissions()">
                                        <option value="">所有科室</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <input type="date" class="form-control" id="admissionDateFilter" onchange="filterAdmissions()" placeholder="选择日期">
                                </div>
                                <div class="col-md-3">
                                    <button class="btn btn-outline-secondary" onclick="resetAdmissionFilter()">
                                        <i class="fas fa-undo me-1"></i>重置筛选
                                    </button>
                                    <button class="btn btn-outline-primary" onclick="loadAdmissions()">
                                        <i class="fas fa-sync-alt me-1"></i>刷新
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>申请ID</th>
                                            <th>患者姓名</th>
                                            <th>联系电话</th>
                                            <th>申请科室</th>
                                            <th>病情描述</th>
                                            <th>申请时间</th>
                                            <th>状态</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="admissionTableBody">
                                        <!-- 动态加载数据 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加科室模态框 -->
    <div class="modal fade" id="addDepartmentModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加科室</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addDepartmentForm">
                        <div class="mb-3">
                            <label for="depName" class="form-label">科室名称 *</label>
                            <input type="text" class="form-control" id="depName" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label for="depInfo" class="form-label">科室描述 *</label>
                            <textarea class="form-control" id="depInfo" name="info" rows="3" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="depLevel" class="form-label">所在楼层 *</label>
                            <select class="form-control" id="depLevel" name="level" required>
                                <option value="">请选择</option>
                                <option value="1楼">1楼</option>
                                <option value="2楼">2楼</option>
                                <option value="3楼">3楼</option>
                                <option value="4楼">4楼</option>
                                <option value="5楼">5楼</option>
                                <option value="6楼">6楼</option>
                                <option value="7楼">7楼</option>
                                <option value="8楼">8楼</option>
                                <option value="9楼">9楼</option>
                                <option value="10楼">10楼</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="depPhone" class="form-label">科室电话 *</label>
                            <input type="tel" class="form-control" id="depPhone" name="phone" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addDepartment()">添加</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑科室模态框 -->
    <div class="modal fade" id="editDepartmentModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑科室</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editDepartmentForm">
                        <input type="hidden" id="editDepId" name="depId">
                        <div class="mb-3">
                            <label for="editDepName" class="form-label">科室名称 *</label>
                            <input type="text" class="form-control" id="editDepName" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label for="editDepInfo" class="form-label">科室描述 *</label>
                            <textarea class="form-control" id="editDepInfo" name="info" rows="3" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="editDepLevel" class="form-label">所在楼层 *</label>
                            <select class="form-control" id="editDepLevel" name="level" required>
                                <option value="">请选择</option>
                                <option value="1楼">1楼</option>
                                <option value="2楼">2楼</option>
                                <option value="3楼">3楼</option>
                                <option value="4楼">4楼</option>
                                <option value="5楼">5楼</option>
                                <option value="6楼">6楼</option>
                                <option value="7楼">7楼</option>
                                <option value="8楼">8楼</option>
                                <option value="9楼">9楼</option>
                                <option value="10楼">10楼</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="editDepPhone" class="form-label">科室电话 *</label>
                            <input type="tel" class="form-control" id="editDepPhone" name="phone" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updateDepartment()">更新</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加医生模态框 -->
    <div class="modal fade" id="addDoctorModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加医生</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addDoctorForm">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="docName" class="form-label">姓名 *</label>
                                <input type="text" class="form-control" id="docName" name="name" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="docSex" class="form-label">性别 *</label>
                                <select class="form-control" id="docSex" name="sex" required>
                                    <option value="">请选择</option>
                                    <option value="男">男</option>
                                    <option value="女">女</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="docAge" class="form-label">年龄 *</label>
                                <input type="number" class="form-control" id="docAge" name="age" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="docTitle" class="form-label">职称 *</label>
                                <input type="text" class="form-control" id="docTitle" name="title" required>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="docMajor" class="form-label">专业 *</label>
                            <input type="text" class="form-control" id="docMajor" name="major" required>
                        </div>
                        <div class="mb-3">
                            <label for="docInfo" class="form-label">医生简介 *</label>
                            <textarea class="form-control" id="docInfo" name="info" rows="3" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="docDepName" class="form-label">所属科室 *</label>
                            <select class="form-control" id="docDepName" name="depName" required>
                                <option value="">请选择科室</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="docPw" class="form-label">初始密码 *</label>
                            <input type="password" class="form-control" id="docPw" name="pw" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addDoctor()">添加</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑医生模态框 -->
    <div class="modal fade" id="editDoctorModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑医生</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editDoctorForm">
                        <input type="hidden" id="editDocId" name="dId">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="editDocName" class="form-label">姓名 *</label>
                                <input type="text" class="form-control" id="editDocName" name="name" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="editDocSex" class="form-label">性别 *</label>
                                <select class="form-control" id="editDocSex" name="sex" required>
                                    <option value="">请选择</option>
                                    <option value="男">男</option>
                                    <option value="女">女</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="editDocAge" class="form-label">年龄 *</label>
                                <input type="number" class="form-control" id="editDocAge" name="age" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="editDocTitle" class="form-label">职称 *</label>
                                <input type="text" class="form-control" id="editDocTitle" name="title" required>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="editDocMajor" class="form-label">专业 *</label>
                            <input type="text" class="form-control" id="editDocMajor" name="major" required>
                        </div>
                        <div class="mb-3">
                            <label for="editDocInfo" class="form-label">医生简介 *</label>
                            <textarea class="form-control" id="editDocInfo" name="info" rows="3" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="editDocDepName" class="form-label">所属科室 *</label>
                            <select class="form-control" id="editDocDepName" name="depName" required>
                                <option value="">请选择科室</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="editDocState" class="form-label">状态 *</label>
                            <select class="form-control" id="editDocState" name="state" required>
                                <option value="1">在职</option>
                                <option value="0">离职</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updateDoctor()">更新</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加排班模态框 -->
    <div class="modal fade" id="addScheduleModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加排班</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addScheduleForm">
                        <div class="mb-3">
                            <label for="scheduleDId" class="form-label">选择医生 *</label>
                            <select class="form-control" id="scheduleDId" name="dId" required>
                                <option value="">请选择医生</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="scheduleDepId" class="form-label">选择科室 *</label>
                            <select class="form-control" id="scheduleDepId" name="DepId" required>
                                <option value="">请选择科室</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="scheduleDate" class="form-label">出诊日期 *</label>
                            <input type="date" class="form-control" id="scheduleDate" name="date" required>
                        </div>
                        <div class="mb-3">
                            <label for="scheduleTime" class="form-label">出诊时段 *</label>
                            <select class="form-control" id="scheduleTime" name="time" required>
                                <option value="">请选择</option>
                                <option value="08:30-09:00">08:30-09:00</option>
                                <option value="09:00-09:30">09:00-09:30</option>
                                <option value="09:30-10:00">09:30-10:00</option>
                                <option value="10:00-10:30">10:00-10:30</option>
                                <option value="14:00-14:30">14:00-14:30</option>
                                <option value="14:30-15:00">14:30-15:00</option>
                                <option value="15:00-15:30">15:00-15:30</option>
                                <option value="15:30-16:00">15:30-16:00</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addSchedule()">添加</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑排班模态框 -->
    <div class="modal fade" id="editScheduleModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑排班</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editScheduleForm">
                        <input type="hidden" id="editScheduleSId" name="sId">
                        <div class="mb-3">
                            <label for="editScheduleDId" class="form-label">选择医生 *</label>
                            <select class="form-control" id="editScheduleDId" name="dId" required>
                                <option value="">请选择医生</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="editScheduleDepId" class="form-label">选择科室 *</label>
                            <select class="form-control" id="editScheduleDepId" name="DepId" required>
                                <option value="">请选择科室</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="editScheduleDate" class="form-label">出诊日期 *</label>
                            <input type="date" class="form-control" id="editScheduleDate" name="date" required>
                        </div>
                        <div class="mb-3">
                            <label for="editScheduleTime" class="form-label">出诊时段 *</label>
                            <select class="form-control" id="editScheduleTime" name="time" required>
                                <option value="">请选择</option>
                                <option value="08:30-09:00">08:30-09:00</option>
                                <option value="09:00-09:30">09:00-09:30</option>
                                <option value="09:30-10:00">09:30-10:00</option>
                                <option value="10:00-10:30">10:00-10:30</option>
                                <option value="14:00-14:30">14:00-14:30</option>
                                <option value="14:30-15:00">14:30-15:00</option>
                                <option value="15:00-15:30">15:00-15:30</option>
                                <option value="15:30-16:00">15:30-16:00</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updateSchedule()">更新</button>
                </div>
            </div>
        </div>
    </div>

    <script src="/js/bootstrap.bundle.min.js"></script>
    <script src="/js/axios.min.js"></script>
    <script>
        // 配置axios
        axios.defaults.baseURL = '';
        
        // 添加请求拦截器
        axios.interceptors.request.use(function (config) {
            const token = localStorage.getItem('token');
            if (token) {
                config.headers.Authorization = token;
            }
            return config;
        });

        // 添加响应拦截器
        axios.interceptors.response.use(
            function (response) {
                return response;
            },
            function (error) {
                if (error.response && error.response.status === 401) {
                    localStorage.removeItem('token');
                    localStorage.removeItem('userInfo');
                    window.location.href = '/login';
                }
                return Promise.reject(error);
            }
        );

        // 页面加载完成后初始化
        // 存储原始数据 - 统一声明在顶部避免初始化错误
        let allDoctors = [];
        let allDepartments = [];
        let allSchedules = [];
        let allReservations = [];
        let allMedicalRecords = [];

        document.addEventListener('DOMContentLoaded', function() {
            loadDashboardData();
        });

        // 显示仪表盘
        function showDashboard() {
            hideAllSections();
            document.getElementById('dashboard').style.display = 'block';
            updateActiveNav('dashboard');
            loadDashboardData();
        }

        // 显示住院审核
        function showAdmissionApproval() {
            hideAllSections();
            document.getElementById('admissionApproval').style.display = 'block';
            updateActiveNav('admissionApproval');
            loadDepartmentFilter();
            loadAdmissions();
        }

        // 加载科室筛选选项
        async function loadDepartmentFilter() {
            try {
                const response = await axios.get('/department/query');
                if (response.data.code === 200) {
                    const departments = response.data.data || [];
                    const select = document.getElementById('admissionDepartmentFilter');
                    select.innerHTML = '<option value="">所有科室</option>';
                    departments.forEach(dept => {
                        const id = dept.depId || dept.depid || dept.DepId || dept.DEPID;
                        const name = dept.depName || dept.depname || dept.DepName || dept.DEPNAME;
                        if (id && name) {
                            select.innerHTML += `<option value="${id}">${name}</option>`;
                        }
                    });
                }
            } catch (error) {
                console.error('加载科室筛选失败:', error);
            }
        }

        // 住院审核相关变量
        let currentApplicationId = null;
        let allApplications = [];

        // 加载住院申请列表 - 使用与doctor_home.html相同的实现逻辑
        async function loadAdmissions() {
            try {
                const tbody = document.getElementById('admissionTableBody');
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">正在加载住院申请...</td></tr>';

                // 获取申请列表
                let response;
                const statusFilter = document.getElementById('admissionStatusFilter')?.value || '';
                
                if (statusFilter !== '') {
                    // 按状态筛选所有申请
                    if (statusFilter === '0') {
                        response = await axios.get('/admission/pending');
                    } else {
                        // 获取所有申请然后前端过滤
                        response = await axios.get('/admission/all');
                        if (response.data.code === 200) {
                            const allApps = response.data.data || [];
                            response.data.data = allApps.filter(app => String(app.aState) === statusFilter);
                        }
                    }
                } else {
                    // 获取所有住院申请数据
                    response = await axios.get('/admission/all');
                }

                if (response.data.code === 200) {
                    allApplications = response.data.data || [];
                    
                    // 获取患者和科室信息
                    const [patientResponse, departmentResponse] = await Promise.all([
                        axios.get('/patient/query').catch(error => {
                            console.error('获取患者信息失败:', error);
                            return { data: { code: 500, data: [] } };
                        }),
                        axios.get('/department/query').catch(error => {
                            console.error('获取科室信息失败:', error);
                            return { data: { code: 500, data: [] } };
                        })
                    ]);

                    const patients = patientResponse.data.code === 200 ? patientResponse.data.data : [];
                    const departments = departmentResponse.data.code === 200 ? departmentResponse.data.data : [];

                    if (window.__DEBUG__) {
                        console.log('获取到的患者数据:', patients);
                        console.log('获取到的科室数据:', departments);
                    }

                    const patientMap = new Map();
                    patients.forEach(p => {
                        const patientId = p.pId || p.pid || p.PId || p.PID;
                        if (patientId) {
                            patientMap.set(patientId, p);
                        }
                    });

                    const departmentMap = new Map();
                    departments.forEach(d => {
                        const depId = d.depId || d.depid || d.DepId;
                        const depName = d.depName || d.depname || d.DepName || `科室${depId}`;
                        if (depId) {
                            departmentMap.set(depId, depName);
                        }
                    });

                    // 渲染表格
                    tbody.innerHTML = '';
                    if (allApplications.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">暂无住院申请</td></tr>';
                        return;
                    }

                    allApplications.forEach(app => {
                        if (window.__DEBUG__) {
                            console.log('处理住院申请:', app);
                            console.log('申请时间字段值:', app.aApplyTime, app.aapplytime, app.AApplyTime);
                        }
                        
                        // 获取患者信息，支持多种字段名格式
                        const patientId = app.pId || app.pid || app.PId || app.PID;
                        const patient = patientMap.get(patientId) || {};
                        const patientName = patient.pName || patient.pname || patient.PName || patient.name || '未知患者';
                        const patientPhone = patient.pPhone || patient.pphone || patient.PPhone || patient.phone || '-';
                        
                        // 获取科室信息，支持多种字段名格式
                        const depId = app.depId || app.depid || app.DepId;
                        const depName = departmentMap.get(depId) || `科室${depId}` || '未知科室';
                        
                        // 获取申请状态和紧急程度
                        const stateValue = app.aState !== undefined ? app.aState : (app.astate !== undefined ? app.astate : app.AState);
                        const statusText = getAdmissionStatusText(stateValue);
                        const statusClass = getAdmissionStatusClass(stateValue);
                        
                        // 格式化申请时间（更强健的字段与格式兼容）
                        let applyTime = '-';
                        try {
                            const pick = (obj, keys) => { for (const k of keys) { if (obj[k] !== undefined && obj[k] !== null && obj[k] !== '') return obj[k]; } };
                            let timeValue = pick(app, [
                                'aApplyTime','aapplytime','AApplyTime','AAPPLYTIME','a_apply_time',
                                'applyTime','ApplyTime','createTime','CreateTime','ctime','gmtCreate','gmtCreated',
                                'aTime','atime','a_time'
                            ]);
                            if (!timeValue) {
                                // 通用兜底：扫描对象中所有包含 time 的字段
                                const entries = Object.entries(app || {}).filter(([k,v]) => /time/i.test(k) && v);
                                if (entries.length) timeValue = entries[0][1];
                            }
                            const parseTime = (val) => {
                                if (!val) return null;
                                try {
                                    if (Array.isArray(val)) return new Date(val[0], (val[1]||1)-1, val[2]||1, val[3]||0, val[4]||0, val[5]||0);
                                    if (typeof val === 'object' && (val.year||val.monthValue||val.dayOfMonth)) {
                                        const y=val.year||val.y, m=(val.monthValue||val.month||1), d0=(val.dayOfMonth||val.day||1);
                                        return new Date(y, m-1, d0, val.hour||0, val.minute||0, val.second||0);
                                    }
                                    if (typeof val === 'number' || (/^\d+$/.test(String(val)))) return new Date(Number(val));
                                    if (typeof val === 'string') {
                                        let s = val.trim();
                                        if (/^\d{4}[./-]\d{1,2}[./-]\d{1,2}/.test(s) || /T/.test(s) || /:\d{2}/.test(s)) {
                                            let d = new Date(s);
                                            if (isNaN(d)) d = new Date(s.replace(' ', 'T'));
                                            if (isNaN(d) && /[./]/.test(s)) d = new Date(s.replace(/[.]/g,'-'));
                                            if (!isNaN(d)) return d;
                                        }
                                    }
                                } catch {}
                                return null;
                            };
                            const d = parseTime(timeValue);
                            if (d && !isNaN(d.getTime())) {
                                applyTime = d.toLocaleString('zh-CN', { year:'numeric', month:'2-digit', day:'2-digit', hour:'2-digit', minute:'2-digit' });
                            }
                        } catch (e) {
                            // 忽略，保持 '-'
                        }

                        // 获取申请编号和病情描述
                        const applicationNumber = app.aNumber || app.anumber || `ADM${app.aId || ''}` || '-';
                        const description = app.aReason || app.areason || app.aDiagnosis || app.adiagnosis || '-';

                        const row = `
                            <tr>
                                <td>${applicationNumber}</td>
                                <td>${patientName}</td>
                                <td>${patientPhone}</td>
                                <td>${depName}</td>
                                <td title="${description}">${description.length > 20 ? description.substring(0, 20) + '...' : description}</td>
                                <td>${applyTime}</td>
                                <td><span class="badge ${statusClass}">${statusText}</span></td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary" onclick="viewApplicationDetail(${app.aId || app.aid || 0})">查看</button>
                                    ${(app.aState === 0 || app.astate === 0) ? `
                                        <button class="btn btn-sm btn-success" onclick="quickApprove(${app.aId || app.aid || 0})">批准</button>
                                        <button class="btn btn-sm btn-danger" onclick="quickReject(${app.aId || app.aid || 0})">拒绝</button>
                                    ` : ''}
                                </td>
                            </tr>
                        `;
                        tbody.innerHTML += row;
                    });
                } else {
                    tbody.innerHTML = `<tr><td colspan="8" class="text-center text-muted">加载失败：${response.data.msg || '未知错误'}</td></tr>`;
                }
            } catch (error) {
                console.error('加载住院申请失败:', error);
                document.getElementById('admissionTableBody').innerHTML = 
                    `<tr><td colspan="8" class="text-center text-muted">加载失败，请检查网络连接</td></tr>`;
            }
        }

if(false){
        // 获取申请状态信息
                    const possibleStates = [app.aState, app.astate, app.AState, app.ASTATE, app.state, app.State];
                    const state = possibleStates.find(s => s !== undefined && s !== null);
                    const finalState = state !== undefined ? state : 0;
                    
                    const statusText = getAdmissionStatusText(finalState);
                    const statusClass = getAdmissionStatusClass(finalState);
                    
                    // 获取申请时间
                    let applyTime = '-';
                    try {
                        const possibleTimes = [app.aApplyTime, app.aapplytime, app.AApplyTime, app.AAPPLYTIME, 
                                             app.applyTime, app.ApplyTime, app.createTime, app.CreateTime];
                        const timeField = possibleTimes.find(time => time !== undefined && time !== null);
                        
                        if (timeField) {
                            const date = new Date(timeField);
                            if (!isNaN(date.getTime())) {
                                applyTime = date.toLocaleString('zh-CN', {
                                    year: 'numeric',
                                    month: '2-digit',
                                    day: '2-digit',
                                    hour: '2-digit',
                                    minute: '2-digit'
                                });
                            }
                        }
                    } catch (e) { 
                        console.log('时间解析失败:', e);
                    }

                    // 获取描述信息
                    const possibleDescriptions = [app.aDescription, app.adescription, app.ADescription, app.ADESCRIPTION, 
                                                app.description, app.Description, app.reason, app.Reason];
                    const description = possibleDescriptions.find(desc => desc && desc.trim()) || '-';
                    
                    // 获取申请ID和编号
                    const possibleIds = [app.aId, app.aid, app.AId, app.AID, app.id, app.Id, app.ID];
                    const appId = possibleIds.find(id => id !== undefined && id !== null);
                    
                    const possibleNumbers = [app.aNumber, app.anumber, app.ANumber, app.ANUMBER, 
                                           app.number, app.Number, app.applicationNumber];
                    const appNumber = possibleNumbers.find(num => num && num.toString().trim()) || appId || `申请${index + 1}`;

                    console.log(`渲染申请 ${index + 1}: ID=${appId}, 编号=${appNumber}, 患者=${patientName}, 科室=${depName}, 状态=${finalState}`);

                    const row = `
                        <tr>
                            <td>${appNumber}</td>
                            <td>${patientName}</td>
                            <td>${patientPhone}</td>
                            <td>${depName}</td>
                            <td title="${description}">${description.length > 20 ? description.substring(0, 20) + '...' : description}</td>
                                <td>${applyTime}</td>
                                <td><span class="badge ${statusClass}">${statusText}</span></td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary" onclick="viewApplicationDetail(${appId})">查看</button>
                                    ${state === 0 ? `
                                        <button class="btn btn-sm btn-success" onclick="quickApprove(${appId})">批准</button>
                                        <button class="btn btn-sm btn-danger" onclick="quickReject(${appId})">拒绝</button>
                                    ` : ''}
                                </td>
                            </tr>
                        `;
                        tbody.innerHTML += row;

                console.log(`住院申请列表渲染完成，共 ${allApplications.length} 条记录`);

                // 存储全局变量供筛选使用
                window.allApplications = allApplications;
                console.error('加载住院申请失败:', error);
                document.getElementById('admissionTableBody').innerHTML = 
                    `<tr><td colspan="8" class="text-center text-muted">加载失败: ${error.message}</td></tr>`;

}
        // 创建测试数据用于演示
        function createTestAdmissionData() {
            const testData = [
                {
                    aId: 1,
                    aNumber: 'ADM20241201001',
                    pId: 1,
                    depId: 1,
                    aDescription: '患者因急性阑尾炎需要住院治疗，病情较重需要尽快安排手术',
                    aApplyTime: '2024-12-01 09:30:00',
                    aState: 0,
                    patientName: '张三',
                    patientPhone: '13800138001',
                    departmentName: '外科'
                },
                {
                    aId: 2,
                    aNumber: 'ADM20241201002',
                    pId: 2,
                    depId: 2,
                    aDescription: '患者心脏病复发，需要住院观察治疗',
                    aApplyTime: '2024-12-01 10:15:00',
                    aState: 1,
                    patientName: '李四',
                    patientPhone: '13800138002',
                    departmentName: '内科'
                },
                {
                    aId: 3,
                    aNumber: 'ADM20241201003',
                    pId: 3,
                    depId: 3,
                    aDescription: '骨折需要手术治疗和康复',
                    aApplyTime: '2024-12-01 11:00:00',
                    aState: 0,
                    patientName: '王五',
                    patientPhone: '13800138003',
                    departmentName: '骨科'
                },
                {
                    aId: 4,
                    aNumber: 'ADM20241201004',
                    pId: 4,
                    depId: 4,
                    aDescription: '儿童发热需要住院观察',
                    aApplyTime: '2024-12-01 14:20:00',
                    aState: 2,
                    patientName: '赵六',
                    patientPhone: '13800138004',
                    departmentName: '儿科'
                },
                {
                    aId: 5,
                    aNumber: 'ADM20241201005',
                    pId: 5,
                    depId: 5,
                    aDescription: '妇科疾病需要住院手术治疗',
                    aApplyTime: '2024-12-01 15:45:00',
                    aState: 0,
                    patientName: '孙七',
                    patientPhone: '13800138005',
                    departmentName: '妇科'
                }
            ];
            
            return testData;
        }

        // 获取关联数据（患者和科室）
        async function fetchRelatedData() {
            try {
                // 尝试多个患者API端点
                const patientEndpoints = ['/patient/query', '/patient/all', '/patient/list'];
                let patientResponse = null;
                
                for (const endpoint of patientEndpoints) {
                    try {
                        const response = await axios.get(endpoint);
                        if (response.data.code === 200 && response.data.data) {
                            patientResponse = response;
                            console.log(`成功从 ${endpoint} 获取患者数据`);
                            break;
                        }
                    } catch (e) {
                        console.log(`患者端点 ${endpoint} 失败:`, e.message);
                    }
                }

                // 尝试多个科室API端点
                const departmentEndpoints = ['/department/query', '/department/all', '/department/list'];
                let departmentResponse = null;
                
                for (const endpoint of departmentEndpoints) {
                    try {
                        const response = await axios.get(endpoint);
                        if (response.data.code === 200 && response.data.data) {
                            departmentResponse = response;
                            console.log(`成功从 ${endpoint} 获取科室数据`);
                            break;
                        }
                    } catch (e) {
                        console.log(`科室端点 ${endpoint} 失败:`, e.message);
                    }
                }

                const patientMap = new Map();
                if (patientResponse && patientResponse.data.code === 200 && Array.isArray(patientResponse.data.data)) {
                    console.log('原始患者数据:', patientResponse.data.data);
                    patientResponse.data.data.forEach(p => {
                        // 尝试所有可能的ID字段名
                        const possibleIds = [p.pId, p.pid, p.PId, p.PID, p.id, p.Id, p.ID, p.patientId, p.PatientId];
                        const id = possibleIds.find(id => id !== undefined && id !== null);
                        
                        if (id) {
                            // 转换为字符串和数字两种格式都存储
                            patientMap.set(String(id), p);
                            patientMap.set(Number(id), p);
                            console.log(`添加患者映射: ID=${id}, 姓名=${p.pName || p.pname || p.PName || p.PNAME || p.name || p.Name}`);
                        }
                    });
                }

                const departmentMap = new Map();
                if (departmentResponse && departmentResponse.data.code === 200 && Array.isArray(departmentResponse.data.data)) {
                    console.log('原始科室数据:', departmentResponse.data.data);
                    departmentResponse.data.data.forEach(d => {
                        // 尝试所有可能的ID和名称字段
                        const possibleIds = [d.depId, d.depid, d.DepId, d.DEPID, d.id, d.Id, d.ID, d.departmentId, d.DepartmentId];
                        const possibleNames = [d.depName, d.depname, d.DepName, d.DEPNAME, d.name, d.Name, d.departmentName, d.DepartmentName];
                        
                        const id = possibleIds.find(id => id !== undefined && id !== null);
                        const name = possibleNames.find(name => name !== undefined && name !== null);
                        
                        if (id && name) {
                            // 转换为字符串和数字两种格式都存储
                            departmentMap.set(String(id), name);
                            departmentMap.set(Number(id), name);
                            console.log(`添加科室映射: ID=${id}, 名称=${name}`);
                        }
                    });
                }
                
                console.log('最终患者映射表大小:', patientMap.size);
                console.log('最终科室映射表大小:', departmentMap.size);
                
                return { patientMap, departmentMap };
            } catch (error) {
                console.error('获取关联数据失败:', error);
                return { patientMap: new Map(), departmentMap: new Map() };
            }
        }

        // 获取申请状态文本
        function getAdmissionStatusText(status) {
            const statusMap = {
                0: '待审批',
                1: '已批准',
                2: '已拒绝',
                3: '已入院',
                4: '已取消'
            };
            return statusMap[status] || '未知状态';
        }

        // 获取申请状态样式
        function getAdmissionStatusClass(status) {
            const classMap = {
                0: 'bg-warning',
                1: 'bg-success',
                2: 'bg-danger',
                3: 'bg-info',
                4: 'bg-secondary'
            };
            return classMap[status] || 'bg-secondary';
        }

        // 获取紧急程度文本
        function getUrgencyText(urgency) {
            const urgencyMap = {
                1: '普通',
                2: '紧急',
                3: '危重'
            };
            return urgencyMap[urgency] || '普通';
        }

        // 获取紧急程度样式
        function getUrgencyClass(urgency) {
            const classMap = {
                1: 'bg-secondary',
                2: 'bg-warning',
                3: 'bg-danger'
            };
            return classMap[urgency] || 'bg-secondary';
        }

        // 快速批准申请
        async function quickApprove(aId) {
            if (confirm('确定要批准这个住院申请吗？')) {
                await approveApplicationById(aId);
            }
        }

        // 快速拒绝申请
        async function quickReject(aId) {
            const reason = prompt('请输入拒绝原因：');
            if (reason && reason.trim()) {
                await rejectApplicationById(aId, reason.trim());
            }
        }

        // 批准申请的具体实现
        async function approveApplicationById(aId) {
            try {
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const approveDoctor = userInfo.dId || userInfo.did || userInfo.id || userInfo.uId || 1; // 管理员默认ID为1
                
                const response = await axios.post(`/admission/approve/${aId}`, null, {
                    params: { approveDoctor: approveDoctor }
                });
                
                if (response.data.code === 200) {
                    alert('申请已批准！');
                    // 刷新列表
                    loadAdmissions();
                } else {
                    alert('批准失败：' + (response.data.msg || '未知错误'));
                }
            } catch (error) {
                console.error('批准申请失败:', error);
                alert('批准失败，请检查网络连接');
            }
        }

        // 拒绝申请的具体实现
        async function rejectApplicationById(aId, reason) {
            try {
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const approveDoctor = userInfo.dId || userInfo.did || userInfo.id || userInfo.uId || 1; // 管理员默认ID为1

                // 统一准备多种字段名，兼容不同后端实现
                const payload = {
                    approveDoctor: Number(approveDoctor),
                    reason: reason,
                    rejectReason: reason,
                    aReason: reason
                };

                let resp = null;
                // 1) 优先 JSON Body
                try {
                    resp = await axios.post(`/admission/reject/${aId}`, payload, { headers: { 'Content-Type': 'application/json' } });
                } catch (_) {}

                // 2) 回退 x-www-form-urlencoded
                if (!resp) {
                    const form = new URLSearchParams();
                    form.append('approveDoctor', String(approveDoctor));
                    form.append('reason', reason);
                    form.append('rejectReason', reason);
                    form.append('aReason', reason);
                    try {
                        resp = await axios.post(`/admission/reject/${aId}`, form, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
                    } catch (_) {}
                }

                // 3) 回退 Query Params（路径含ID）
                if (!resp) {
                    try {
                        resp = await axios.post(`/admission/reject/${aId}`, null, {
                            params: {
                                approveDoctor: Number(approveDoctor),
                                reason: reason,
                                rejectReason: reason,
                                aReason: reason
                            }
                        });
                    } catch (_) {}
                }

                // 4) 回退 不带ID路径 + aId 作为参数（部分后端用这种形态）
                if (!resp) {
                    try {
                        const form2 = new URLSearchParams();
                        form2.append('aId', String(aId));
                        form2.append('approveDoctor', String(approveDoctor));
                        form2.append('reason', reason);
                        form2.append('rejectReason', reason);
                        form2.append('aReason', reason);
                        resp = await axios.post(`/admission/reject`, form2, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
                    } catch (_) {}
                }

                // 5) 回退 PUT 方法
                if (!resp) {
                    try {
                        resp = await axios.put(`/admission/reject/${aId}`, payload, { headers: { 'Content-Type': 'application/json' } });
                    } catch (_) {}
                }
                if (!resp) {
                    try {
                        resp = await axios.put(`/admission/reject`, payload, { params: { aId: aId } });
                    } catch (_) {}
                }

                if (resp && resp.data && resp.data.code === 200) {
                    alert('申请已拒绝！');
                    loadAdmissions();
                } else {
                    const msg = resp?.data?.msg || resp?.data?.message || '未知错误';
                    alert('拒绝失败：' + msg);
                }
            } catch (error) {
                console.error('拒绝申请失败:', error);
                const msg = error?.response?.data?.msg || error?.message || '网络错误';
                alert('拒绝失败：' + msg);
            }
        }

        // 查看申请详情（健壮字段兼容 + 多接口兜底）
        async function viewApplicationDetail(aId) {
            try {
                currentApplicationId = aId;
                let resp = null;
                try { resp = await axios.get(`/admission/info/${aId}`); } catch (_) {}
                if (!resp || resp.data?.code !== 200) {
                    try { resp = await axios.get(`/admission/detail/${aId}`); } catch (_) {}
                }
                if (!resp || resp.data?.code !== 200 || !resp.data?.data) {
                    alert('获取申请详情失败');
                    return;
                }
                const app = resp.data.data || {};
                const pick = (obj, keys, def='-') => { for (const k of keys) { if (obj && obj[k] !== undefined && obj[k] !== null && obj[k] !== '') return obj[k]; } return def; };
                const fmtTime = (v) => {
                    if (!v) return '-';
                    try {
                        if (Array.isArray(v)) { const d = new Date(v[0], (v[1]||1)-1, v[2]||1, v[3]||0, v[4]||0, v[5]||0); return isNaN(d)?'-':d.toLocaleString(); }
                        if (typeof v === 'object' && v.year && (v.monthValue||v.month) && (v.dayOfMonth||v.day)) {
                            const d = new Date(v.year, (v.monthValue||v.month)-1, (v.dayOfMonth||v.day), v.hour||0, v.minute||0, v.second||0); return isNaN(d)?'-':d.toLocaleString();
                        }
                        const d = new Date(v); return isNaN(d)?'-':d.toLocaleString();
                    } catch { return '-'; }
                };
                const appId = pick(app, ['aId','aid','id','AId','AID'], '-');
                const appNumber = pick(app, ['aNumber','anumber','number','applicationNumber'], appId);
                const applyTimeRaw = pick(app, ['aApplyTime','aapplytime','AAPPLYTIME','AApplyTime','applyTime','createTime','a_apply_time'], null);
                const applyTime = fmtTime(applyTimeRaw);
                const description = pick(app, ['aReason','areason','aDescription','adescription','aDiagnosis','adiagnosis','reason','description'], '-');
                const wType = pick(app, ['wType','wtype'], '-');
                const stateVal = Number(pick(app, ['aState','astate','AState','state'], 0));
                const depId = pick(app, ['depId','depid','DepId','departmentId'], null);
                let depName = pick(app, ['depName','depname','departmentName'], null);
                if (!depName) {
                    if (depId && depId !== '-') {
                        try { const depR = await axios.get(`/department/Info/${depId}`); if (depR.data?.code === 200) depName = pick(depR.data.data, ['depName','depname','name'], `科室${depId}`); } catch {}
                    }
                    if (!depName) {
                        try { const allDep = await axios.get('/department/query'); if (allDep.data?.code === 200) { const hit = (allDep.data.data||[]).find(d => String(pick(d,['depId','depid','id'], '')) === String(depId)); if (hit) depName = pick(hit,['depName','depname','name'], `科室${depId}`); } } catch {}
                    }
                    if (!depName) depName = depId ? `科室${depId}` : '未知科室';
                }
                const pId = pick(app, ['pId','pid','patientId'], null);
                let patient = {};
                if (pId && pId !== '-') { try { const pR = await axios.get(`/patient/info/${pId}`); if (pR.data?.code === 200) patient = pR.data.data || {}; } catch {} }
                const pName = pick(patient, ['pName','pname','name'], pick(app, ['pName','pname','patientName'], '-'));
                const pGender = pick(patient, ['pGender','pgender','gender'], '-');
                const pAge = pick(patient, ['pAge','page','age'], '-');
                const pPhone = pick(patient, ['pPhone','pphone','phone'], pick(app, ['patientPhone','phone'], '-'));
                const pIdCard = pick(patient, ['pIdCard','pidcard','idCard','idcard'], '-');
                const lines = [
                    '申请详情：','',
                    '申请信息',
                    `申请编号：${appNumber || '-'}`,
                    `申请时间：${applyTime}`,
                    `病情描述：${description}`,
                    `申请科室：${depName}`,
                    `病房类型：${wType}`,
                    `状态：${getAdmissionStatusText([0,1,2,3,4].includes(stateVal) ? stateVal : 0)}`,
                    '',
                    '患者信息',
                    `姓名：${pName}`,
                    `性别：${pGender}`,
                    `年龄：${pAge}`,
                    `电话：${pPhone}`,
                    `身份证：${pIdCard}`
                ];
                alert(lines.join('\n'));
            } catch (error) {
                console.error('获取申请详情失败:', error);
                alert('获取申请详情失败，请检查网络连接');
            }
        }

        // 筛选功能
        function filterAdmissions() {
            const searchTerm = document.getElementById('admissionSearch').value.toLowerCase();
            const statusFilter = document.getElementById('admissionStatusFilter').value;
            const departmentFilter = document.getElementById('admissionDepartmentFilter').value;
            const dateFilter = document.getElementById('admissionDateFilter').value;

            if (!allApplications || allApplications.length === 0) {
                loadAdmissions();
                return;
            }

            let filteredApplications = [...allApplications];

            // 状态筛选
            if (statusFilter !== '') {
                filteredApplications = filteredApplications.filter(app => {
                    const state = app.aState || app.astate;
                    return String(state) === statusFilter;
                });
            }

            // 科室筛选
            if (departmentFilter !== '') {
                filteredApplications = filteredApplications.filter(app => {
                    const depId = app.depId || app.depid || app.DepId || app.DEPID;
                    return String(depId) === departmentFilter;
                });
            }

            // 日期筛选
            if (dateFilter) {
                filteredApplications = filteredApplications.filter(app => {
                    const timeField = app.aApplyTime || app.aapplytime || app.AApplyTime || app.AAPPLYTIME;
                    if (timeField) {
                        const appDate = new Date(timeField).toISOString().split('T')[0];
                        return appDate === dateFilter;
                    }
                    return false;
                });
            }

            // 文本搜索（患者姓名）
            if (searchTerm) {
                renderFilteredApplications(filteredApplications, searchTerm);
            } else {
                renderFilteredApplications(filteredApplications);
            }
        }

        // 渲染筛选后的申请列表
        async function renderFilteredApplications(applications, searchTerm = '') {
            const tbody = document.getElementById('admissionTableBody');
            const { patientMap, departmentMap } = await fetchRelatedData();

            tbody.innerHTML = '';
            if (applications.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">无匹配的住院申请</td></tr>';
                return;
            }

            applications.forEach(app => {
                const patientId = app.pId || app.pid || app.PId || app.PID;
                const patient = patientMap.get(patientId) || {};
                const patientName = patient.pName || patient.pname || patient.PName || patient.PNAME || '未知患者';
                
                // 如果有搜索词，检查患者姓名是否匹配
                if (searchTerm && !patientName.toLowerCase().includes(searchTerm)) {
                    return;
                }

                const patientPhone = patient.pPhone || patient.pphone || patient.PPhone || patient.PPHONE || '-';
                
                const depId = app.depId || app.depid || app.DepId || app.DEPID;
                const depName = departmentMap.get(depId) || '未知科室';
                
                const statusText = getAdmissionStatusText(app.aState || app.astate);
                const statusClass = getAdmissionStatusClass(app.aState || app.astate);
                
                let applyTime = '-';
                try {
                    const timeField = app.aApplyTime || app.aapplytime || app.AApplyTime || app.AAPPLYTIME;
                    if (timeField) {
                        const date = new Date(timeField);
                        if (!isNaN(date.getTime())) {
                            applyTime = date.toLocaleString();
                        }
                    }
                } catch (e) { 
                    console.log('时间解析失败:', e);
                }

                const description = app.aDescription || app.adescription || app.ADescription || app.ADESCRIPTION || '-';
                const appId = app.aId || app.aid || app.AId || app.AID;
                const appNumber = app.aNumber || app.anumber || app.ANumber || app.ANUMBER || appId || '-';

                const row = `
                    <tr>
                        <td>${appNumber}</td>
                        <td>${patientName}</td>
                        <td>${patientPhone}</td>
                        <td>${depName}</td>
                        <td title="${description}">${description.length > 20 ? description.substring(0, 20) + '...' : description}</td>
                        <td>${applyTime}</td>
                        <td><span class="badge ${statusClass}">${statusText}</span></td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary" onclick="viewApplicationDetail(${appId})">查看</button>
                            ${(app.aState || app.astate) === 0 ? `
                                <button class="btn btn-sm btn-success" onclick="quickApprove(${appId})">批准</button>
                                <button class="btn btn-sm btn-danger" onclick="quickReject(${appId})">拒绝</button>
                            ` : ''}
                        </td>
                    </tr>
                `;
                tbody.innerHTML += row;
            });
        }

        // 重置筛选
        function resetAdmissionFilter() {
            document.getElementById('admissionSearch').value = '';
            document.getElementById('admissionStatusFilter').value = '';
            document.getElementById('admissionDepartmentFilter').value = '';
            document.getElementById('admissionDateFilter').value = '';
            loadAdmissions();
        }

        // 刷新数据
        function refreshAdmissionData() {
            loadAdmissions();
        }

        // 显示统计
        function showAdmissionStatistics() {
            alert('统计功能开发中...');
        }

        // 显示科室管理
        function showDepartmentManagement() {
            hideAllSections();
            document.getElementById('departmentManagement').style.display = 'block';
            updateActiveNav('departmentManagement');
            loadDepartments();
        }

        // 显示医生管理
        function showDoctorManagement() {
            hideAllSections();
            document.getElementById('doctorManagement').style.display = 'block';
            updateActiveNav('doctorManagement');
            loadDoctors();
        }

        // 显示排班管理
        function showScheduleManagement() {
            hideAllSections();
            document.getElementById('scheduleManagement').style.display = 'block';
            updateActiveNav('scheduleManagement');
            loadSchedules();
        }

        // 显示预约管理
        function showReservationManagement() {
            hideAllSections();
            document.getElementById('reservationManagement').style.display = 'block';
            updateActiveNav('reservationManagement');
            loadReservations();
        }

        // 显示病历管理
        function showMedicalRecordManagement() {
            hideAllSections();
            document.getElementById('medicalRecordManagement').style.display = 'block';
            updateActiveNav('medicalRecordManagement');
            loadMedicalRecords();
        }

        // 隐藏所有内容区域
        function hideAllSections() {
            const sections = document.querySelectorAll('.content-section');
            sections.forEach(section => {
                section.style.display = 'none';
            });
        }

        // 更新活跃导航
        function updateActiveNav(activeId) {
            const navLinks = document.querySelectorAll('.nav-link');
            navLinks.forEach(link => {
                link.classList.remove('active');
            });
            // 这里可以根据activeId设置对应的导航为活跃状态
        }

        // 加载仪表盘数据
        async function loadDashboardData() {
            try {
                // 这里可以加载统计数据
                document.getElementById('departmentCount').textContent = '12';
                document.getElementById('doctorCount').textContent = '45';
                document.getElementById('patientCount').textContent = '1280';
                document.getElementById('reservationCount').textContent = '23';
            } catch (error) {
                console.error('加载仪表盘数据失败:', error);
            }
        }

        // 存储原始科室数据（在医生管理部分重新声明）
        // let allDepartments = [];

        // 加载科室数据
        async function loadDepartments() {
            const tbody = document.getElementById('departmentTableBody');
            
            try {
                // 显示加载状态
                tbody.innerHTML = '<tr><td colspan="6" class="text-center"><div class="spinner-border spinner-border-sm me-2"></div>加载中...</td></tr>';
                
                const response = await axios.get('/department/query');
                console.log('科室数据响应:', response.data);
                
                if (response.data.code === 200) {
                    allDepartments = response.data.data || [];
                    displayDepartments(allDepartments);
                } else {
                    tbody.innerHTML = '<tr><td colspan="6" class="text-center text-danger">加载失败：' + response.data.msg + '</td></tr>';
                }
            } catch (error) {
                console.error('加载科室数据失败:', error);
                tbody.innerHTML = '<tr><td colspan="6" class="text-center text-danger">加载失败，请检查网络连接</td></tr>';
            }
        }

        // 显示科室数据
        function displayDepartments(departments) {
            const tbody = document.getElementById('departmentTableBody');
            tbody.innerHTML = '';
            
            if (departments && departments.length > 0) {
                departments.forEach(dept => {
                    const createTime = dept.depCreateTime ? new Date(dept.depCreateTime).toLocaleDateString() : '-';
                    const row = `
                        <tr>
                            <td>${dept.depName || '-'}</td>
                            <td>${dept.depLevel || '-'}</td>
                            <td>${dept.depPhone || '-'}</td>
                            <td>${createTime}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary btn-action" onclick="editDepartment(${dept.depId})" title="编辑">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-danger btn-action" onclick="deleteDepartment(${dept.depId})" title="删除">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                    `;
                    tbody.innerHTML += row;
                });
            } else {
                tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">暂无科室数据</td></tr>';
            }
        }

        // 筛选科室
        function filterDepartments() {
            const searchTerm = document.getElementById('departmentSearch').value.toLowerCase();
            const floorFilter = document.getElementById('departmentLevelFilter').value;
            
            let filteredDepartments = allDepartments.filter(dept => {
                const nameMatch = !searchTerm || (dept.depName && dept.depName.toLowerCase().includes(searchTerm));
                const floorMatch = !floorFilter || dept.depLevel === floorFilter;
                return nameMatch && floorMatch;
            });
            
            displayDepartments(filteredDepartments);
        }

        // 重置筛选
        function resetDepartmentFilter() {
            document.getElementById('departmentSearch').value = '';
            document.getElementById('departmentLevelFilter').value = '';
            displayDepartments(allDepartments);
        }

        // 统一的API调用函数
        async function apiCall(url, method = 'GET', data = null) {
            try {
                const config = {
                    method: method,
                    url: url,
                    headers: {
                        'Content-Type': 'application/json'
                    }
                };
                if (data) {
                    config.data = data;
                }
                const response = await axios(config);
                return { success: true, data: response.data };
            } catch (error) {
                console.error(`API调用失败 [${method} ${url}]:`, error);
                return { 
                    success: false, 
                    error: error.response?.data?.msg || error.message || '网络请求失败'
                };
            }
        }

        // 显示加载状态
        function showLoadingState(elementId, message = '加载中...', colspan = 8) {
            const element = document.getElementById(elementId);
            if (element) {
                element.innerHTML = `<tr><td colspan="${colspan}" class="text-center">
                    <div class="spinner-border spinner-border-sm me-2"></div>${message}
                </td></tr>`;
            }
        }

        // 显示错误状态
        function showErrorState(elementId, message, colspan = 8) {
            const element = document.getElementById(elementId);
            if (element) {
                element.innerHTML = `<tr><td colspan="${colspan}" class="text-center text-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>${message}
                </td></tr>`;
            }
        }

        // 通用安全取值与多字段取值工具（供排班搜索/筛选复用）
        function safeGet(obj, prop, defaultValue = '-') {
            return obj && obj[prop] !== undefined && obj[prop] !== null ? obj[prop] : defaultValue;
        }

        function getFieldValue(obj, possibleNames, defaultValue = '') {
            for (const name of possibleNames) {
                if (obj && obj[name] !== undefined && obj[name] !== null) {
                    return obj[name];
                }
            }
            return defaultValue;
        }

        // 加载医生数据
        async function loadDoctors() {
            const tbody = document.getElementById('doctorTableBody');
            
            try {
                // 显示加载状态
                showLoadingState('doctorTableBody', '正在加载医生数据...');
                
                console.log('开始加载医生数据...');
                
                // 并行加载科室和医生数据
                const [depResult, doctorResult] = await Promise.allSettled([
                    loadDepartmentsData(),
                    loadAllDoctorsData()
                ]);
                
                console.log('科室数据加载结果:', depResult);
                console.log('医生数据加载结果:', doctorResult);
                
                // 检查科室数据加载结果
                if (depResult.status === 'rejected' || !depResult.value.success) {
                    console.error('科室数据加载失败:', depResult);
                    showErrorState('doctorTableBody', '加载科室数据失败，无法显示医生信息');
                    return;
                }
                
                allDepartments = depResult.value.data.data || [];
                console.log('科室数据:', allDepartments);
                
                // 检查医生数据加载结果
                if (doctorResult.status === 'rejected' || !doctorResult.value.success) {
                    console.error('医生数据加载失败:', doctorResult);
                    showErrorState('doctorTableBody', '加载医生数据失败：' + (doctorResult.value?.error || '未知错误'));
                    return;
                }
                
                allDoctors = doctorResult.value.data.data || [];
                console.log('医生数据:', allDoctors);
                
                // 显示数据
                displayDoctors(allDoctors);
                loadDoctorFilterOptions(allDepartments);
                
                // 显示成功消息
                console.log(`成功加载 ${allDoctors.length} 名医生数据`);
                
            } catch (error) {
                console.error('加载医生数据失败:', error);
                showErrorState('doctorTableBody', '加载失败，请检查网络连接');
            }
        }

        // 加载科室数据
        async function loadDepartmentsData() {
            return await apiCall('/department/query');
        }

        // 加载所有医生数据
        async function loadAllDoctorsData() {
            // 优先使用新的获取所有医生接口
            const result = await apiCall('/doctor/query');
            if (result.success) {
                // 处理Map格式的数据，转换为前端需要的格式
                const doctors = result.data.data || [];
                const processedDoctors = doctors.map(doctor => {
                    // 将数据库字段名转换为前端期望的字段名
                    return {
                        dId: doctor.did || doctor.dId,
                        dName: doctor.dname || doctor.dName,
                        dSex: doctor.dsex || doctor.dSex,
                        dAge: doctor.dage || doctor.dAge,
                        dTitle: doctor.dtitle || doctor.dTitle,
                        dMajor: doctor.dmajor || doctor.dMajor,
                        dInfo: doctor.dinfo || doctor.dInfo,
                        dState: doctor.dstate || doctor.dState,
                        depId: doctor.depid || doctor.depId,
                        depName: doctor.depName || '未知科室',
                        dCreateTime: doctor.dcreatetime || doctor.dCreateTime
                    };
                });
                
                return {
                    success: true,
                    data: { code: 200, data: processedDoctors }
                };
            }
            
            // 如果新接口失败，回退到逐科室加载方式
            console.warn('使用新接口失败，回退到逐科室加载方式');
            return await loadDoctorsByDepartment();
        }

        // 逐科室加载医生数据（备用方案）
        async function loadDoctorsByDepartment() {
            const depResult = await loadDepartmentsData();
            if (!depResult.success) {
                return { success: false, error: '无法加载科室数据' };
            }
            
            const departments = depResult.data.data || [];
            let allDoctors = [];
            let errors = [];
            
            // 并行加载所有科室的医生数据
            const doctorPromises = departments.map(async (dept) => {
                try {
                    const result = await apiCall(`/doctor/query/${dept.depId}`);
                    if (result.success && result.data.code === 200) {
                        const doctors = result.data.data || [];
                        // 为每个医生添加科室信息
                        doctors.forEach(doctor => {
                            doctor.depName = dept.depName;
                            doctor.depId = dept.depId;
                        });
                        return doctors;
                    } else {
                        errors.push(`科室 ${dept.depName} 加载失败: ${result.error}`);
                        return [];
                    }
                } catch (error) {
                    errors.push(`科室 ${dept.depName} 加载异常: ${error.message}`);
                    return [];
                }
            });
            
            const results = await Promise.all(doctorPromises);
            allDoctors = results.flat();
            
            if (errors.length > 0) {
                console.warn('部分科室医生数据加载失败:', errors);
            }
            
            return {
                success: true,
                data: { code: 200, data: allDoctors }
            };
        }

        // 加载医生筛选选项
        function loadDoctorFilterOptions(departments) {
            const departmentSelect = document.getElementById('doctorDepartmentFilter');
            departmentSelect.innerHTML = '<option value="">所有科室</option>';
            
            departments.forEach(dept => {
                const option = document.createElement('option');
                option.value = dept.depName;
                option.textContent = dept.depName;
                departmentSelect.appendChild(option);
            });
        }

        // 显示医生数据
        function displayDoctors(doctors) {
            const tbody = document.getElementById('doctorTableBody');
            if (!tbody) {
                console.error('找不到医生表格体元素');
                return;
            }
            
            tbody.innerHTML = '';
            
            if (!doctors || !Array.isArray(doctors) || doctors.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted"><i class="fas fa-info-circle me-2"></i>暂无医生数据</td></tr>';
                return;
            }
            
            try {
                doctors.forEach((doctor, index) => {
                    // 验证医生数据完整性
                    if (!doctor || typeof doctor !== 'object') {
                        console.warn(`医生数据格式错误，索引: ${index}`, doctor);
                        return;
                    }
                    
                    const stateText = doctor.dState === 1 ? '在职' : '离职';
                    const stateClass = doctor.dState === 1 ? 'text-success' : 'text-danger';
                    const stateIcon = doctor.dState === 1 ? 'fa-check-circle' : 'fa-times-circle';
                    
                    // 安全地获取医生属性，避免undefined错误
                    const safeGet = (obj, prop, defaultValue = '-') => {
                        return obj && obj[prop] !== undefined && obj[prop] !== null ? obj[prop] : defaultValue;
                    };
                    
                    const row = `
                        <tr data-doctor-id="${safeGet(doctor, 'dId', '')}">
                            <td>${safeGet(doctor, 'dName')}</td>
                            <td>${safeGet(doctor, 'dSex')}</td>
                            <td>${safeGet(doctor, 'dAge')}</td>
                            <td>${safeGet(doctor, 'dTitle')}</td>
                            <td>${safeGet(doctor, 'dMajor')}</td>
                            <td>${safeGet(doctor, 'depName')}</td>
                            <td>
                                <span class="${stateClass}">
                                    <i class="fas ${stateIcon} me-1"></i>${stateText}
                                </span>
                            </td>
                            <td>
                                <div class="btn-group" role="group">
                                    <button class="btn btn-sm btn-outline-primary btn-action" 
                                            onclick="editDoctor(${safeGet(doctor, 'dId', 0)})" 
                                            title="编辑医生信息"
                                            ${!doctor.dId ? 'disabled' : ''}>
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger btn-action" 
                                            onclick="deleteDoctor(${safeGet(doctor, 'dId', 0)})" 
                                            title="删除医生"
                                            ${!doctor.dId ? 'disabled' : ''}>
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `;
                    tbody.innerHTML += row;
                });
                
                console.log(`成功显示 ${doctors.length} 名医生数据`);
            } catch (error) {
                console.error('显示医生数据时发生错误:', error);
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-danger"><i class="fas fa-exclamation-triangle me-2"></i>显示数据时发生错误</td></tr>';
            }
        }

        // 筛选医生
        function filterDoctors() {
            try {
                const searchTerm = document.getElementById('doctorSearch')?.value?.toLowerCase() || '';
                const departmentFilter = document.getElementById('doctorDepartmentFilter')?.value || '';
                const stateFilter = document.getElementById('doctorStateFilter')?.value || '';
                
                if (!allDoctors || !Array.isArray(allDoctors)) {
                    console.warn('医生数据未加载或格式错误');
                    displayDoctors([]);
                    return;
                }
                
                const filteredDoctors = allDoctors.filter(doctor => {
                    if (!doctor || typeof doctor !== 'object') return false;
                    
                    // 姓名匹配
                    const nameMatch = !searchTerm || 
                        (doctor.dName && doctor.dName.toLowerCase().includes(searchTerm));
                    
                    // 科室匹配
                    const departmentMatch = !departmentFilter || 
                        (doctor.depName && doctor.depName === departmentFilter);
                    
                    // 状态匹配
                    const stateMatch = !stateFilter || 
                        (doctor.dState !== undefined && doctor.dState.toString() === stateFilter);
                    
                    return nameMatch && departmentMatch && stateMatch;
                });
                
                displayDoctors(filteredDoctors);
                console.log(`筛选结果: ${filteredDoctors.length}/${allDoctors.length} 名医生`);
                
            } catch (error) {
                console.error('筛选医生时发生错误:', error);
                displayDoctors([]);
            }
        }

        // 重置医生筛选
        function resetDoctorFilter() {
            try {
                const searchInput = document.getElementById('doctorSearch');
                const departmentSelect = document.getElementById('doctorDepartmentFilter');
                const stateSelect = document.getElementById('doctorStateFilter');
                
                if (searchInput) searchInput.value = '';
                if (departmentSelect) departmentSelect.value = '';
                if (stateSelect) stateSelect.value = '';
                
                displayDoctors(allDoctors);
                console.log('医生筛选已重置');
            } catch (error) {
                console.error('重置筛选时发生错误:', error);
            }
        }

        // 排班数据已在顶部声明

        // 加载排班数据
        async function loadSchedules() {
            const tbody = document.getElementById('scheduleTableBody');
            
            try {
                // 显示加载状态
                showLoadingState('scheduleTableBody', '正在加载排班数据...');
                
                console.log('开始加载排班数据...');
                
                // 获取排班数据（包含医生信息）
                let result = await apiCall('/schedule/queryWithDoctorInfo');
                // 某些后端未实现该接口时，退回到 /schedule/query
                if (!result.success || result.data.code !== 200) {
                    result = await apiCall('/schedule/query');
                }
                
                if (!result.success) {
                    console.error('排班数据加载失败:', result);
                    showErrorState('scheduleTableBody', '加载排班数据失败：' + result.error);
                    return;
                }
                
                allSchedules = (result.data && result.data.data) ? result.data.data : [];
                console.log('排班数据:', allSchedules);
                
                // 调试：打印第一条数据的字段
                if (allSchedules.length > 0) {
                    console.log('第一条排班数据的字段:', Object.keys(allSchedules[0]));
                    console.log('第一条排班数据详情:', allSchedules[0]);
                    console.log('日期字段值:', allSchedules[0].date, allSchedules[0].Date, allSchedules[0].schedule_date);
                    console.log('时段字段值:', allSchedules[0].time, allSchedules[0].Time, allSchedules[0].schedule_time);
                }
                
                // 新API已经包含医生信息，不需要额外加载
                // 直接显示数据
                displaySchedules(allSchedules);
                loadScheduleFilterOptions();
                
                console.log(`成功加载 ${allSchedules.length} 条排班数据`);
                
            } catch (error) {
                console.error('加载排班数据失败:', error);
                showErrorState('scheduleTableBody', '加载失败，请检查网络连接');
            }
        }

        // 加载排班显示所需的数据（医生和科室信息）
        async function loadScheduleDisplayData() {
            try {
                // 获取医生数据
                const doctorResult = await apiCall('/doctor/query');
                if (doctorResult.success) {
                    const doctors = doctorResult.data.data || [];
                    allSchedules.forEach(schedule => {
                        const doctor = doctors.find(d => d.dId === schedule.dId);
                        if (doctor) {
                            schedule.doctorName = doctor.dName;
                            schedule.depName = doctor.depName;
                        }
                    });
                }
                
                // 获取科室数据
                const depResult = await apiCall('/department/query');
                if (depResult.success) {
                    const departments = depResult.data.data || [];
                    allSchedules.forEach(schedule => {
                        if (!schedule.depName) {
                            const dept = departments.find(d => d.depId === schedule.depId);
                            if (dept) {
                                schedule.depName = dept.depName;
                            }
                        }
                    });
                }
            } catch (error) {
                console.error('加载排班显示数据失败:', error);
            }
        }

        // 显示排班数据
        function displaySchedules(schedules) {
            const tbody = document.getElementById('scheduleTableBody');
            if (!tbody) {
                console.error('找不到排班表格体元素');
                return;
            }
            
            tbody.innerHTML = '';
            
            if (!schedules || !Array.isArray(schedules) || schedules.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted"><i class="fas fa-info-circle me-2"></i>暂无排班数据</td></tr>';
                return;
            }
            
            try {
                schedules.forEach((schedule, index) => {
                    // 验证排班数据完整性
                    if (!schedule || typeof schedule !== 'object') {
                        console.warn(`排班数据格式错误，索引: ${index}`, schedule);
                        return;
                    }
                    
                    // 调试：打印每条数据的字段
                    if (index === 0) {
                        console.log('第一条排班数据的所有字段:', schedule);
                        console.log('日期相关字段:', {
                            date: schedule.date,
                            Date: schedule.Date,
                            schedule_date: schedule.schedule_date
                        });
                        console.log('时段相关字段:', {
                            time: schedule.time,
                            Time: schedule.Time,
                            schedule_time: schedule.schedule_time
                        });
                    }
                    
                    // 安全地获取排班属性
                    const safeGet = (obj, prop, defaultValue = '-') => {
                        return obj && obj[prop] !== undefined && obj[prop] !== null ? obj[prop] : defaultValue;
                    };
                    
                    // 智能获取字段值，尝试多种可能的字段名
                    const getFieldValue = (obj, possibleNames, defaultValue = '-') => {
                        for (const name of possibleNames) {
                            if (obj && obj[name] !== undefined && obj[name] !== null) {
                                return obj[name];
                            }
                        }
                        return defaultValue;
                    };
                    
                    // 处理日期显示 - 尝试多种可能的字段名
                    let dateStr = '-';
                    let dateValue = getFieldValue(schedule, ['date', 'Date', 'schedule_date', 'DATE']);
                    if (dateValue && dateValue !== '-') {
                        try {
                            // 处理不同的日期格式
                            if (typeof dateValue === 'string') {
                                // 如果是字符串，尝试解析
                                if (dateValue.includes('-')) {
                                    dateStr = new Date(dateValue).toLocaleDateString();
                                } else {
                                    dateStr = dateValue;
                                }
                            } else if (dateValue.toLocaleDateString) {
                                dateStr = dateValue.toLocaleDateString();
                            } else {
                                dateStr = dateValue.toString();
                            }
                        } catch (e) {
                            console.warn('日期解析失败:', dateValue, e);
                            dateStr = dateValue.toString();
                        }
                    }
                    
                    const remainClass = schedule.remain > 5 ? 'text-success' : schedule.remain > 0 ? 'text-warning' : 'text-danger';
                    
                    const row = `
                        <tr data-schedule-id="${safeGet(schedule, 'sId', '')}">
                            <td>${safeGet(schedule, 'sId')}</td>
                            <td>${safeGet(schedule, 'dname') || safeGet(schedule, 'doctorName') || safeGet(schedule, 'dName')}</td>
                            <td>${safeGet(schedule, 'depName')}</td>
                            <td>${dateStr}</td>
                            <td>${getFieldValue(schedule, ['time', 'Time', 'schedule_time', 'TIME'])}</td>
                            <td><span class="${remainClass}">${safeGet(schedule, 'remain')}</span></td>
                            <td>${safeGet(schedule, 'already')}</td>
                            <td>
                                <div class="btn-group" role="group">
                                    <button class="btn btn-sm btn-outline-primary btn-action" 
                                            onclick="editSchedule(${safeGet(schedule, 'sId', 0)})" 
                                            title="编辑排班"
                                            ${!schedule.sId ? 'disabled' : ''}>
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger btn-action" 
                                            onclick="deleteSchedule(${safeGet(schedule, 'sId', 0)})" 
                                            title="删除排班"
                                            ${!schedule.sId ? 'disabled' : ''}>
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `;
                    tbody.innerHTML += row;
                });
                
                console.log(`成功显示 ${schedules.length} 条排班数据`);
            } catch (error) {
                console.error('显示排班数据时发生错误:', error);
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-danger"><i class="fas fa-exclamation-triangle me-2"></i>显示数据时发生错误</td></tr>';
            }
        }

        // 加载排班筛选选项
        function loadScheduleFilterOptions() {
            // 加载科室筛选选项
            const departmentSelect = document.getElementById('scheduleDepartmentFilter');
            if (departmentSelect) {
                departmentSelect.innerHTML = '<option value="">所有科室</option>';
                const departments = [...new Set(allSchedules.map(s => s.depName).filter(Boolean))];
                departments.forEach(dept => {
                    const option = document.createElement('option');
                    option.value = dept;
                    option.textContent = dept;
                    departmentSelect.appendChild(option);
                });
            }
        }

        // 筛选排班
        function filterSchedules() {
            try {
                const searchTerm = document.getElementById('scheduleSearch')?.value?.toLowerCase() || '';
                const departmentFilter = document.getElementById('scheduleDepartmentFilter')?.value || '';
                const dateFilter = document.getElementById('scheduleDateFilter')?.value || '';
                const timeFilter = document.getElementById('scheduleTimeFilter')?.value || '';
                
                if (!allSchedules || !Array.isArray(allSchedules)) {
                    console.warn('排班数据未加载或格式错误');
                    displaySchedules([]);
                    return;
                }
                
                const filteredSchedules = allSchedules.filter(schedule => {
                    if (!schedule || typeof schedule !== 'object') return false;
                    
                    // 医生姓名匹配
                    const doctorName = getFieldValue(schedule, ['dName', 'dname', 'doctorName', 'name'], '');
                    const nameMatch = !searchTerm || (doctorName && doctorName.toLowerCase().includes(searchTerm));
                    
                    // 科室匹配
                    const depName = getFieldValue(schedule, ['depName', 'department', 'dep_name'], '');
                    const departmentMatch = !departmentFilter || (depName === departmentFilter);
                    
                    // 日期匹配
                    let dateMatch = true;
                    if (dateFilter) {
                        try {
                            let scheduleDateStr = '';
                            const dateValue = getFieldValue(schedule, ['date', 'Date', 'schedule_date', 'DATE']);
                            if (dateValue && dateValue !== '-') {
                                if (typeof dateValue === 'string') {
                                    scheduleDateStr = new Date(dateValue).toISOString().split('T')[0];
                                } else if (dateValue && dateValue.toISOString) {
                                    scheduleDateStr = dateValue.toISOString().split('T')[0];
                                } else {
                                    scheduleDateStr = String(dateValue);
                                }
                            }
                            dateMatch = scheduleDateStr === dateFilter;
                        } catch (e) {
                            dateMatch = false;
                        }
                    }
                    
                    // 时段匹配
                    const timeValue = getFieldValue(schedule, ['time', 'Time', 'schedule_time', 'TIME']);
                    const timeMatch = !timeFilter || (timeValue && timeValue === timeFilter);
                    
                    return nameMatch && departmentMatch && dateMatch && timeMatch;
                });
                
                displaySchedules(filteredSchedules);
                console.log(`筛选结果: ${filteredSchedules.length}/${allSchedules.length} 条排班`);
                
            } catch (error) {
                console.error('筛选排班时发生错误:', error);
                displaySchedules([]);
            }
        }

        // 重置排班筛选
        function resetScheduleFilter() {
            try {
                const searchInput = document.getElementById('scheduleSearch');
                const departmentSelect = document.getElementById('scheduleDepartmentFilter');
                const dateInput = document.getElementById('scheduleDateFilter');
                const timeSelect = document.getElementById('scheduleTimeFilter');
                
                if (searchInput) searchInput.value = '';
                if (departmentSelect) departmentSelect.value = '';
                if (dateInput) dateInput.value = '';
                if (timeSelect) timeSelect.value = '';
                
                displaySchedules(allSchedules);
                console.log('排班筛选已重置');
            } catch (error) {
                console.error('重置筛选时发生错误:', error);
            }
        }

        // 刷新排班数据
        async function refreshScheduleData() {
            console.log('手动刷新排班数据...');
            await loadSchedules();
        }

        // 将任意日期形态统一为 yyyy-MM-dd
        function normalizeYMD(val){
            if(!val) return '';
            try{
                if(typeof val === 'string'){
                    let s = val.split('T')[0].trim();
                    s = s.replace(/\./g,'-').replace(/\//g,'-');
                    const ps = s.split('-').filter(Boolean);
                    if(ps.length===3){
                        const y = ps[0];
                        const m = ps[1].padStart(2,'0');
                        const d = ps[2].padStart(2,'0');
                        return `${y}-${m}-${d}`;
                    }
                    const d2 = new Date(val);
                    if(!isNaN(d2)) return d2.toISOString().split('T')[0];
                    return '';
                }
                if(val instanceof Date){
                    if(!isNaN(val)) return val.toISOString().split('T')[0];
                    return '';
                }
                const d3 = new Date(val);
                if(!isNaN(d3)) return d3.toISOString().split('T')[0];
                return '';
            }catch{ return ''; }
        }

        // 统一的排班创建调用：优先使用 GET + query（兼容后端 @GetMapping），失败再尝试 POST
        async function callSetSchedule(dId, depId, date, time) {
            const ymd = normalizeYMD(date);
            try {
                // 1) 后端是 @GetMapping("/setSchedule")，优先 GET + query
                const url = `/schedule/setSchedule?dId=${encodeURIComponent(dId)}&depId=${encodeURIComponent(depId)}&date=${encodeURIComponent(ymd)}&time=${encodeURIComponent(time)}`;
                let res = await axios.get(url);
                if (res && res.data && res.data.code === 200) return res;
            } catch (e) {
                // ignore and try POST fallback
            }
            try {
                // 2) Fallback: POST + 正确字段名（大多数实现）
                let res = await axios.post('/schedule/setSchedule', { dId, depId, date: ymd, time });
                if (res && res.data && res.data.code === 200) return res;
            } catch (e) {
                // ignore and try another payload variant
            }
            try {
                // 3) 仍不行：尝试 DepId 大写的变体（曾出现过的后端实现）
                let res = await axios.post('/schedule/setSchedule', { dId, DepId: depId, date: ymd, time });
                return res;
            } catch (e) {
                throw e;
            }
        }

        // 批量添加未来排班示例数据，便于患者预约
        async function seedFutureSchedules() {
            try {
                // 拉取科室与医生
                const [depRes, docRes] = await Promise.all([
                    apiCall('/department/query'),
                    apiCall('/doctor/query')
                ]);
                if (!depRes.success || !docRes.success) {
                    alert('无法获取科室或医生信息，请先确认已添加科室与医生');
                    return;
                }
                const departments = depRes.data.data || [];
                const doctors = (docRes.data.data || []).slice(0, 4); // 取前4位医生示例
                if (doctors.length === 0 || departments.length === 0) {
                    alert('请先添加科室与医生后再尝试');
                    return;
                }

                const dayMs = 24 * 60 * 60 * 1000;
                const toYMD = (d) => {
                    const y = d.getFullYear();
                    const m = String(d.getMonth() + 1).padStart(2, '0');
                    const dd = String(d.getDate()).padStart(2, '0');
                    return `${y}-${m}-${dd}`;
                };

                let success = 0; let fail = 0;
                for (let i = 0; i < doctors.length; i++) {
                    const doctor = doctors[i] || {};
                    const dId = doctor.dId || doctor.did || doctor.id;
                    // 通过医生的 depId 或 depName 反查科室id
                    let depId = doctor.depId || doctor.depid;
                    if (!depId && doctor.depName) {
                        const match = departments.find(d => d.depName === doctor.depName);
                        if (match) depId = match.depId;
                    }
                    if (!dId || !depId) { fail++; continue; }

                    // 安排未来1~4天的上午/下午
                    const date = new Date(Date.now() + (i + 1) * dayMs);
                    const ymd = toYMD(date);
                    const time = i % 2 === 0 ? '上午' : '下午';

                    try {
                        const res = await callSetSchedule(dId, depId, ymd, time);
                        if (res && res.data && res.data.code === 200) success++; else fail++;
                    } catch (e) {
                        console.error('创建排班失败:', e);
                        fail++;
                    }
                }

                alert(`示例排班添加完成：成功 ${success} 条，失败 ${fail} 条`);
                await loadSchedules();
            } catch (e) {
                console.error('批量添加示例排班失败:', e);
                alert('批量添加示例排班失败，请查看控制台日志');
            }
        }

        // 覆盖/实现单条添加排班：从"添加排班"模态框读取并调用 callSetSchedule
        async function addSchedule() {
            try {
                const dId = document.getElementById('scheduleDId')?.value;
                const depId = document.getElementById('scheduleDepId')?.value;
                const date = normalizeYMD(document.getElementById('scheduleDate')?.value);
                const time = document.getElementById('scheduleTime')?.value;
                if (!dId || !depId || !date || !time) {
                    alert('请完整选择医生、科室、日期与时段');
                    return;
                }
                const res = await callSetSchedule(dId, depId, date, time);
                if (res && res.data && res.data.code === 200) {
                    alert('添加排班成功');
                    bootstrap.Modal.getInstance(document.getElementById('addScheduleModal'))?.hide();
                    await loadSchedules();
                } else {
                    alert('添加失败：' + (res?.data?.msg || '未知错误'));
                }
            } catch (e) {
                console.error('添加排班失败:', e);
                alert('添加失败，请查看控制台日志');
            }
        }

        // 预约数据已在顶部声明

        // 加载预约数据
        async function loadReservations() {
                const tbody = document.getElementById('reservationTableBody');
            
            try {
                // 显示加载状态
                showLoadingState('reservationTableBody', '正在加载预约数据...');
                
                console.log('开始加载预约数据...');
                
                const result = await apiCall('/reservation/queryAll');
                
                if (!result.success) {
                    console.error('预约数据加载失败:', result);
                    showErrorState('reservationTableBody', '加载预约数据失败：' + result.error);
                    return;
                }
                
                allReservations = result.data.data || [];
                console.log('预约数据:', allReservations);
                
                // 调试：打印第一条数据的字段
                if (allReservations.length > 0) {
                    console.log('第一条预约数据的字段:', Object.keys(allReservations[0]));
                    console.log('第一条预约数据详情:', allReservations[0]);
                }
                
                // 显示数据
                displayReservations(allReservations);
                loadReservationFilterOptions();
                
                console.log(`成功加载 ${allReservations.length} 条预约数据`);
                
            } catch (error) {
                console.error('加载预约数据失败:', error);
                showErrorState('reservationTableBody', '加载失败，请检查网络连接');
            }
        }

        // 显示预约数据
        function displayReservations(reservations) {
            const tbody = document.getElementById('reservationTableBody');
            if (!tbody) {
                console.error('找不到预约表格体元素');
                return;
            }
            
            tbody.innerHTML = '';
            
            if (!reservations || !Array.isArray(reservations) || reservations.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted"><i class="fas fa-info-circle me-2"></i>暂无预约数据</td></tr>';
                return;
            }
            
            try {
                reservations.forEach((reservation, index) => {
                    // 验证预约数据完整性
                    if (!reservation || typeof reservation !== 'object') {
                        console.warn(`预约数据格式错误，索引: ${index}`, reservation);
                        return;
                    }
                    
                    // 安全地获取预约属性
                    const safeGet = (obj, prop, defaultValue = '-') => {
                        return obj && obj[prop] !== undefined && obj[prop] !== null ? obj[prop] : defaultValue;
                    };
                    
                    // 处理状态显示
                    const getStateInfo = (state) => {
                        switch (state) {
                            case 0: return { text: '待就诊', class: 'text-warning', icon: 'fa-clock' };
                            case 1: return { text: '已就诊', class: 'text-success', icon: 'fa-check-circle' };
                            case 2: return { text: '已取消', class: 'text-danger', icon: 'fa-times-circle' };
                            default: return { text: '未知', class: 'text-muted', icon: 'fa-question-circle' };
                        }
                    };
                    
                    const stateInfo = getStateInfo(reservation.rState);
                    
                    // 处理预约时间显示
                    let reservationTimeStr = '-';
                    if (reservation.rTime) {
                        try {
                            if (typeof reservation.rTime === 'string') {
                                reservationTimeStr = new Date(reservation.rTime).toLocaleString();
                            } else {
                                reservationTimeStr = reservation.rTime.toLocaleString();
                            }
                        } catch (e) {
                            reservationTimeStr = reservation.rTime.toString();
                        }
                    }
                    
                    const row = `
                        <tr data-reservation-id="${safeGet(reservation, 'rId', '')}">
                            <td>${safeGet(reservation, 'rId')}</td>
                            <td>${safeGet(reservation, 'pname')}</td>
                            <td>${safeGet(reservation, 'dname')}</td>
                            <td>${safeGet(reservation, 'depName')}</td>
                            <td>${reservationTimeStr}</td>
                            <td>${safeGet(reservation, 'rNum')}</td>
                            <td>
                                <span class="${stateInfo.class}">
                                    <i class="fas ${stateInfo.icon} me-1"></i>${stateInfo.text}
                                </span>
                            </td>
                            <td>
                                <div class="btn-group" role="group">
                                    <button class="btn btn-sm btn-outline-info btn-action" 
                                            onclick="viewReservationDetail(${safeGet(reservation, 'rId', 0)})" 
                                            title="查看详情"
                                            ${!reservation.rId ? 'disabled' : ''}>
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    ${reservation.rState === 0 ? `
                                    <button class="btn btn-sm btn-outline-danger btn-action" 
                                            onclick="cancelReservation(${safeGet(reservation, 'rId', 0)})" 
                                            title="取消预约"
                                            ${!reservation.rId ? 'disabled' : ''}>
                                        <i class="fas fa-ban"></i>
                                    </button>
                                    ` : ''}
                                </div>
                            </td>
                        </tr>
                    `;
                    tbody.innerHTML += row;
                });
                
                console.log(`成功显示 ${reservations.length} 条预约数据`);
            } catch (error) {
                console.error('显示预约数据时发生错误:', error);
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-danger"><i class="fas fa-exclamation-triangle me-2"></i>显示数据时发生错误</td></tr>';
            }
        }

        // 加载预约筛选选项
        function loadReservationFilterOptions() {
            // 加载医生筛选选项
            const doctorSelect = document.getElementById('reservationDoctorFilter');
            if (doctorSelect) {
                doctorSelect.innerHTML = '<option value="">所有医生</option>';
                const doctors = [...new Set(allReservations.map(r => r.dname).filter(Boolean))];
                doctors.forEach(doctor => {
                    const option = document.createElement('option');
                    option.value = doctor;
                    option.textContent = doctor;
                    doctorSelect.appendChild(option);
                });
            }
            
            // 加载科室筛选选项
            const departmentSelect = document.getElementById('reservationDepartmentFilter');
            if (departmentSelect) {
                departmentSelect.innerHTML = '<option value="">所有科室</option>';
                const departments = [...new Set(allReservations.map(r => r.depName).filter(Boolean))];
                departments.forEach(dept => {
                    const option = document.createElement('option');
                    option.value = dept;
                    option.textContent = dept;
                    departmentSelect.appendChild(option);
                });
            }
        }

        // 筛选预约
        function filterReservations() {
            try {
                const searchTerm = document.getElementById('reservationSearch')?.value?.toLowerCase() || '';
                const doctorFilter = document.getElementById('reservationDoctorFilter')?.value || '';
                const departmentFilter = document.getElementById('reservationDepartmentFilter')?.value || '';
                const stateFilter = document.getElementById('reservationStateFilter')?.value || '';
                
                if (!allReservations || !Array.isArray(allReservations)) {
                    console.warn('预约数据未加载或格式错误');
                    displayReservations([]);
                    return;
                }
                
                const filteredReservations = allReservations.filter(reservation => {
                    if (!reservation || typeof reservation !== 'object') return false;
                    
                    // 患者姓名匹配
                    const nameMatch = !searchTerm || 
                        (reservation.pname && reservation.pname.toLowerCase().includes(searchTerm));
                    
                    // 医生匹配
                    const doctorMatch = !doctorFilter || 
                        (reservation.dname && reservation.dname === doctorFilter);
                    
                    // 科室匹配
                    const departmentMatch = !departmentFilter || 
                        (reservation.depName && reservation.depName === departmentFilter);
                    
                    // 状态匹配
                    const stateMatch = !stateFilter || 
                        (reservation.rState !== undefined && reservation.rState.toString() === stateFilter);
                    
                    return nameMatch && doctorMatch && departmentMatch && stateMatch;
                });
                
                displayReservations(filteredReservations);
                console.log(`筛选结果: ${filteredReservations.length}/${allReservations.length} 条预约`);
                
            } catch (error) {
                console.error('筛选预约时发生错误:', error);
                displayReservations([]);
            }
        }

        // 重置预约筛选
        function resetReservationFilter() {
            try {
                const searchInput = document.getElementById('reservationSearch');
                const doctorSelect = document.getElementById('reservationDoctorFilter');
                const departmentSelect = document.getElementById('reservationDepartmentFilter');
                const stateSelect = document.getElementById('reservationStateFilter');
                
                if (searchInput) searchInput.value = '';
                if (doctorSelect) doctorSelect.value = '';
                if (departmentSelect) departmentSelect.value = '';
                if (stateSelect) stateSelect.value = '';
                
                displayReservations(allReservations);
                console.log('预约筛选已重置');
            } catch (error) {
                console.error('重置筛选时发生错误:', error);
            }
        }

        // 刷新预约数据
        async function refreshReservationData() {
            console.log('手动刷新预约数据...');
            await loadReservations();
        }

        // 查看预约详情（兼容多字段命名 + 拉取医生/时段信息）
        async function viewReservationDetail(rId) {
            try {
                if (!rId || rId <= 0) {
                    alert('无效的预约ID');
                    return;
                }

                const result = await apiCall(`/reservation/info/${rId}`);
                if (!result.success || result.data.code !== 200 || !result.data.data) {
                    alert('获取预约详情失败：' + (result.error || result.data?.msg || '未知错误'));
                    return;
                }

                const rez = result.data.data || {};

                // 兼容不同字段命名
                const pick = (obj, names, def = undefined) => {
                    for (const n of names) {
                        if (obj && obj[n] !== undefined && obj[n] !== null) return obj[n];
                    }
                    return def;
                };

                const rIdVal = pick(rez, ['rId','rid','RId','RID']);
                const pIdVal = pick(rez, ['pId','pid','PId','PID']);
                const sIdVal = pick(rez, ['sId','sid','SId','SID']);
                const rTimeVal = pick(rez, ['rTime','rtime','r_time']);
                const rNumVal = pick(rez, ['rNum','rnum','r_num']);
                const rStateVal = pick(rez, ['rState','rstate','r_state'], -1);
                const rInfoVal = pick(rez, ['rInfo','rinfo','r_info'], '');

                // 进一步拉取排班, 医生与科室信息
                let dateStr = '-';
                let timeStr = '-';
                let doctorName = '-';
                let depName = '-';
                if (sIdVal) {
                    try {
                        const schedAll = await apiCall('/schedule/query');
                        if (schedAll.success && schedAll.data.code === 200) {
                            const schedules = schedAll.data.data || [];
                            const sch = schedules.find(s => (s.sId || s.sid) === sIdVal) || {};
                            // 日期
                            const dv = pick(sch, ['date','Date','schedule_date']);
                            if (dv) {
                                try {
                                    if (typeof dv === 'string') {
                                        dateStr = dv.split('T')[0];
                                    } else {
                                        const d = new Date(dv);
                                        if (!isNaN(d)) dateStr = d.toISOString().split('T')[0];
                                    }
                                } catch { dateStr = String(dv); }
                            }
                            // 时段
                            timeStr = pick(sch, ['time','Time','schedule_time'], '-');
                            // 医生
                            const dId = pick(sch, ['dId','did']);
                            if (dId) {
                                try {
                                    const docRes = await apiCall(`/doctor/info/${dId}`);
                                    if (docRes.success && docRes.data.code === 200 && docRes.data.data) {
                                        const d = docRes.data.data;
                                        doctorName = d.dName || d.dname || '-';
                                        if (d.depId) {
                                            const depRes = await apiCall(`/department/Info/${d.depId}`);
                                            if (depRes.success && depRes.data.code === 200 && depRes.data.data) {
                                                depName = depRes.data.data.depName || depName;
                                            }
                                        }
                                    }
                                } catch {}
                            }
                        }
                    } catch {}
                }

                const stateText = rStateVal === 0 ? '待就诊' : rStateVal === 1 ? '已就诊' : rStateVal === 2 ? '已取消' : '未知';

                const message = `
预约详情：
预约ID：${rIdVal ?? '-'}
患者ID：${pIdVal ?? '-'}
排班ID：${sIdVal ?? '-'}
预约时间：${rTimeVal || '-'}
预约号：${rNumVal || '-'}
状态：${stateText}
备注：${rInfoVal || '无'}

医生：${doctorName}
科室：${depName}
日期：${dateStr}
时段：${timeStr}
                `;
                alert(message);
            } catch (error) {
                console.error('查看预约详情失败:', error);
                alert('查看预约详情失败，请检查网络连接');
            }
        }

        // 取消预约
        async function cancelReservation(rId) {
            try {
                if (!rId || rId <= 0) {
                    alert('无效的预约ID');
                    return;
                }
                
                // 确认取消
                if (!confirm('确定要取消这个预约吗？\n\n取消后将无法恢复！')) {
                    return;
                }
                
                // 显示加载状态
                const loadingMessage = document.createElement('div');
                loadingMessage.className = 'alert alert-info text-center';
                loadingMessage.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>正在取消预约...';
                
                // 在页面顶部显示加载状态
                const container = document.querySelector('.main-content');
                if (container) {
                    container.insertBefore(loadingMessage, container.firstChild);
                }
                
                const result = await apiCall(`/reservation/delete/${rId}`, 'DELETE');
                
                // 移除加载状态
                if (loadingMessage.parentNode) {
                    loadingMessage.parentNode.removeChild(loadingMessage);
                }
                
                if (result.success && result.data.code === 200) {
                    alert('预约取消成功！');
                    await loadReservations(); // 重新加载预约列表
                } else {
                    alert('取消失败：' + (result.error || result.data?.msg || '未知错误'));
                }
                
            } catch (error) {
                console.error('取消预约失败:', error);
                alert('取消失败，请检查网络连接');
            }
        }

        // 导出预约数据
        function exportReservationData() {
            try {
                if (!allReservations || allReservations.length === 0) {
                    alert('没有预约数据可导出');
                    return;
                }
                
                const headers = ['预约ID', '患者', '医生', '科室', '预约时间', '预约号', '状态'];
                const csvContent = [
                    headers.join(','),
                    ...allReservations.map(reservation => [
                        reservation.rId || '',
                        reservation.pname || '',
                        reservation.dname || '',
                        reservation.depName || '',
                        reservation.rTime || '',
                        reservation.rNum || '',
                        reservation.rState === 0 ? '待就诊' : reservation.rState === 1 ? '已就诊' : '已取消'
                    ].join(','))
                ].join('\n');
                
                const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', `预约数据_${new Date().toISOString().split('T')[0]}.csv`);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                console.log('预约数据导出成功');
            } catch (error) {
                console.error('导出预约数据失败:', error);
                alert('导出失败，请重试');
            }
        }

        // 显示预约统计信息
        function showReservationStatistics() {
            if (!allReservations || allReservations.length === 0) {
                alert('暂无预约数据');
                return;
            }
            
            const stats = {
                total: allReservations.length,
                pending: allReservations.filter(r => r.rState === 0).length,
                completed: allReservations.filter(r => r.rState === 1).length,
                cancelled: allReservations.filter(r => r.rState === 2).length,
                byDepartment: {}
            };
            
            allReservations.forEach(reservation => {
                const depName = reservation.depName || '未知科室';
                if (!stats.byDepartment[depName]) {
                    stats.byDepartment[depName] = 0;
                }
                stats.byDepartment[depName]++;
            });
            
            const message = `
预约统计信息：
总预约数：${stats.total}
待就诊：${stats.pending}
已就诊：${stats.completed}
已取消：${stats.cancelled}

各科室分布：
${Object.entries(stats.byDepartment)
    .map(([dep, count]) => `${dep}：${count}个`)
    .join('\n')}
            `;
            alert(message);
        }

        // 病历数据已在顶部声明

        // 加载病历数据
        async function loadMedicalRecords() {
                const tbody = document.getElementById('medicalRecordTableBody');
            
            try {
                // 显示加载状态
                showLoadingState('medicalRecordTableBody', '正在加载病历数据...');
                
                console.log('开始加载病历数据...');
                
                const result = await apiCall('/medical/record/queryAll');
                
                if (!result.success) {
                    console.error('病历数据加载失败:', result);
                    showErrorState('medicalRecordTableBody', '加载病历数据失败：' + result.error);
                    return;
                }
                
                allMedicalRecords = result.data.data || [];
                console.log('病历数据:', allMedicalRecords);
                
                // 调试：打印第一条数据的字段
                if (allMedicalRecords.length > 0) {
                    console.log('第一条病历数据的字段:', Object.keys(allMedicalRecords[0]));
                    console.log('第一条病历数据详情:', allMedicalRecords[0]);
                }
                
                // 显示数据
                displayMedicalRecords(allMedicalRecords);
                loadMedicalRecordFilterOptions();
                
                console.log(`成功加载 ${allMedicalRecords.length} 条病历数据`);
                
            } catch (error) {
                console.error('加载病历数据失败:', error);
                showErrorState('medicalRecordTableBody', '加载失败，请检查网络连接');
            }
        }

        // 显示病历数据
        function displayMedicalRecords(medicalRecords) {
            const tbody = document.getElementById('medicalRecordTableBody');
            if (!tbody) {
                console.error('找不到病历表格体元素');
                return;
            }
            
            tbody.innerHTML = '';
            
            if (!medicalRecords || !Array.isArray(medicalRecords) || medicalRecords.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted"><i class="fas fa-info-circle me-2"></i>暂无病历数据</td></tr>';
                return;
            }
            
            try {
                medicalRecords.forEach((record, index) => {
                    // 验证病历数据完整性
                    if (!record || typeof record !== 'object') {
                        console.warn(`病历数据格式错误，索引: ${index}`, record);
                        return;
                    }
                    
                    // 安全地获取病历属性
                    const safeGet = (obj, prop, defaultValue = '-') => {
                        return obj && obj[prop] !== undefined && obj[prop] !== null ? obj[prop] : defaultValue;
                    };
                    
                    // 处理创建时间显示
                    let createTimeStr = '-';
                    if (record.mTime) {
                        try {
                            if (typeof record.mTime === 'string') {
                                createTimeStr = new Date(record.mTime).toLocaleString();
                            } else {
                                createTimeStr = record.mTime.toLocaleString();
                            }
                        } catch (e) {
                            createTimeStr = record.mTime.toString();
                        }
                    }
                    
                    // 处理诊断结果显示（截取前50个字符）
                    let resultText = safeGet(record, 'mResult');
                    if (resultText && resultText.length > 50) {
                        resultText = resultText.substring(0, 50) + '...';
                    }
                    
                    const row = `
                        <tr data-medical-record-id="${safeGet(record, 'mId', '')}">
                            <td>${safeGet(record, 'mId')}</td>
                            <td>${safeGet(record, 'reservationId') || safeGet(record, 'rId')}</td>
                            <td>${safeGet(record, 'pname')}</td>
                            <td>${safeGet(record, 'dname')}</td>
                            <td>${safeGet(record, 'depName')}</td>
                            <td title="${safeGet(record, 'mResult')}">${resultText}</td>
                            <td>${createTimeStr}</td>
                            <td>
                                <div class="btn-group" role="group">
                                    <button class="btn btn-sm btn-outline-info btn-action" 
                                            onclick="viewMedicalRecordDetail(${safeGet(record, 'mId', 0)})" 
                                            title="查看详情"
                                            ${!record.mId ? 'disabled' : ''}>
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <button class="btn btn-sm btn-outline-primary btn-action" 
                                            onclick="editMedicalRecord(${safeGet(record, 'mId', 0)})" 
                                            title="编辑病历"
                                            ${!record.mId ? 'disabled' : ''}>
                                        <i class="fas fa-edit"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `;
                    tbody.innerHTML += row;
                });
                
                console.log(`成功显示 ${medicalRecords.length} 条病历数据`);
            } catch (error) {
                console.error('显示病历数据时发生错误:', error);
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-danger"><i class="fas fa-exclamation-triangle me-2"></i>显示数据时发生错误</td></tr>';
            }
        }

        // 加载病历筛选选项
        function loadMedicalRecordFilterOptions() {
            // 加载医生筛选选项
            const doctorSelect = document.getElementById('medicalRecordDoctorFilter');
            if (doctorSelect) {
                doctorSelect.innerHTML = '<option value="">所有医生</option>';
                const doctors = [...new Set(allMedicalRecords.map(r => r.dname).filter(Boolean))];
                doctors.forEach(doctor => {
                    const option = document.createElement('option');
                    option.value = doctor;
                    option.textContent = doctor;
                    doctorSelect.appendChild(option);
                });
            }
            
            // 加载科室筛选选项
            const departmentSelect = document.getElementById('medicalRecordDepartmentFilter');
            if (departmentSelect) {
                departmentSelect.innerHTML = '<option value="">所有科室</option>';
                const departments = [...new Set(allMedicalRecords.map(r => r.depName).filter(Boolean))];
                departments.forEach(dept => {
                    const option = document.createElement('option');
                    option.value = dept;
                    option.textContent = dept;
                    departmentSelect.appendChild(option);
                });
            }
        }

        // 筛选病历
        function filterMedicalRecords() {
            try {
                const searchTerm = document.getElementById('medicalRecordSearch')?.value?.toLowerCase() || '';
                const doctorFilter = document.getElementById('medicalRecordDoctorFilter')?.value || '';
                const departmentFilter = document.getElementById('medicalRecordDepartmentFilter')?.value || '';
                const dateFilter = document.getElementById('medicalRecordDateFilter')?.value || '';
                
                if (!allMedicalRecords || !Array.isArray(allMedicalRecords)) {
                    console.warn('病历数据未加载或格式错误');
                    displayMedicalRecords([]);
                    return;
                }
                
                const filteredRecords = allMedicalRecords.filter(record => {
                    if (!record || typeof record !== 'object') return false;
                    
                    // 患者姓名匹配
                    const nameMatch = !searchTerm || 
                        (record.pname && record.pname.toLowerCase().includes(searchTerm));
                    
                    // 医生匹配
                    const doctorMatch = !doctorFilter || 
                        (record.dname && record.dname === doctorFilter);
                    
                    // 科室匹配
                    const departmentMatch = !departmentFilter || 
                        (record.depName && record.depName === departmentFilter);
                    
                    // 日期匹配
                    let dateMatch = true;
                    if (dateFilter) {
                        try {
                            let recordDateStr = '';
                            if (record.mTime) {
                                if (typeof record.mTime === 'string') {
                                    recordDateStr = new Date(record.mTime).toISOString().split('T')[0];
                                } else {
                                    recordDateStr = record.mTime.toISOString().split('T')[0];
                                }
                            }
                            dateMatch = recordDateStr === dateFilter;
                        } catch (e) {
                            dateMatch = false;
                        }
                    }
                    
                    return nameMatch && doctorMatch && departmentMatch && dateMatch;
                });
                
                displayMedicalRecords(filteredRecords);
                console.log(`筛选结果: ${filteredRecords.length}/${allMedicalRecords.length} 条病历`);
                
            } catch (error) {
                console.error('筛选病历时发生错误:', error);
                displayMedicalRecords([]);
            }
        }

        // 重置病历筛选
        function resetMedicalRecordFilter() {
            try {
                const searchInput = document.getElementById('medicalRecordSearch');
                const doctorSelect = document.getElementById('medicalRecordDoctorFilter');
                const departmentSelect = document.getElementById('medicalRecordDepartmentFilter');
                const dateInput = document.getElementById('medicalRecordDateFilter');
                
                if (searchInput) searchInput.value = '';
                if (doctorSelect) doctorSelect.value = '';
                if (departmentSelect) departmentSelect.value = '';
                if (dateInput) dateInput.value = '';
                
                displayMedicalRecords(allMedicalRecords);
                console.log('病历筛选已重置');
            } catch (error) {
                console.error('重置筛选时发生错误:', error);
            }
        }

        // 刷新病历数据
        async function refreshMedicalRecordData() {
            console.log('手动刷新病历数据...');
            await loadMedicalRecords();
        }

        // 查看病历详情
        async function viewMedicalRecordDetail(mId) {
            try {
                if (!mId || mId <= 0) {
                    alert('无效的病历ID');
                    return;
                }
                
                // 从已加载的数据中查找病历
                const record = allMedicalRecords.find(r => r.mId === mId);
                if (!record) {
                    alert('病历信息不存在');
                    return;
                }
                
                // 显示病历详情
                const message = `
病历详情：
病历ID：${record.mId}
预约ID：${record.reservationId || record.rId}
患者：${record.pname || '-'}
医生：${record.dname || '-'}
科室：${record.depName || '-'}
创建时间：${record.mTime || '-'}

诊断结果：
${record.mResult || '无'}

病历信息：
${record.mInfo || '无'}

医嘱建议：
${record.mAdvice || '无'}
                `;
                alert(message);
                
            } catch (error) {
                console.error('查看病历详情失败:', error);
                alert('查看病历详情失败，请检查网络连接');
            }
        }

        // 编辑病历
        async function editMedicalRecord(mId) {
            try {
                if (!mId || mId <= 0) {
                    alert('无效的病历ID');
                    return;
                }
                
                // 从已加载的数据中查找病历
                const record = allMedicalRecords.find(r => r.mId === mId);
                if (!record) {
                    alert('病历信息不存在');
                    return;
                }
                
                // 显示编辑提示
                alert('病历编辑功能需要医生权限，请联系相关医生进行修改。\n\n病历ID：' + mId);
                
            } catch (error) {
                console.error('编辑病历失败:', error);
                alert('编辑病历失败，请检查网络连接');
            }
        }

        // 导出病历数据
        function exportMedicalRecordData() {
            try {
                if (!allMedicalRecords || allMedicalRecords.length === 0) {
                    alert('没有病历数据可导出');
                    return;
                }
                
                const headers = ['病历ID', '预约ID', '患者', '医生', '科室', '诊断结果', '创建时间'];
                const csvContent = [
                    headers.join(','),
                    ...allMedicalRecords.map(record => [
                        record.mId || '',
                        record.reservationId || record.rId || '',
                        record.pname || '',
                        record.dname || '',
                        record.depName || '',
                        (record.mResult || '').replace(/,/g, ';'), // 替换逗号避免CSV格式问题
                        record.mTime || ''
                    ].join(','))
                ].join('\n');
                
                const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', `病历数据_${new Date().toISOString().split('T')[0]}.csv`);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                console.log('病历数据导出成功');
            } catch (error) {
                console.error('导出病历数据失败:', error);
                alert('导出失败，请重试');
            }
        }

        // 显示病历统计信息
        function showMedicalRecordStatistics() {
            if (!allMedicalRecords || allMedicalRecords.length === 0) {
                alert('暂无病历数据');
                return;
            }
            
            const stats = {
                total: allMedicalRecords.length,
                byDepartment: {},
                byDoctor: {},
                recentCount: 0
            };
            
            // 计算最近7天的病历数量
            const sevenDaysAgo = new Date();
            sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
            
            allMedicalRecords.forEach(record => {
                // 按科室统计
                const depName = record.depName || '未知科室';
                if (!stats.byDepartment[depName]) {
                    stats.byDepartment[depName] = 0;
                }
                stats.byDepartment[depName]++;
                
                // 按医生统计
                const doctorName = record.dname || '未知医生';
                if (!stats.byDoctor[doctorName]) {
                    stats.byDoctor[doctorName] = 0;
                }
                stats.byDoctor[doctorName]++;
                
                // 最近7天统计
                if (record.mTime) {
                    try {
                        const recordDate = new Date(record.mTime);
                        if (recordDate >= sevenDaysAgo) {
                            stats.recentCount++;
                        }
                    } catch (e) {
                        // 忽略日期解析错误
                    }
                }
            });
            
            const message = `
病历统计信息：
总病历数：${stats.total}
最近7天：${stats.recentCount}

各科室分布：
${Object.entries(stats.byDepartment)
    .map(([dep, count]) => `${dep}：${count}份`)
    .join('\n')}

医生工作量：
${Object.entries(stats.byDoctor)
    .map(([doctor, count]) => `${doctor}：${count}份`)
    .join('\n')}
            `;
            alert(message);
        }
        // 显示订单管理
        function showOrderManagement(){
            hideAllSections();
            document.getElementById('orderManagement').style.display = 'block';
            updateActiveNav('orderManagement');
            loadAllOrders();
        }

        async function loadAllOrders(){
            const tbody = document.getElementById('ordersTableBody');
            const status = document.getElementById('orderStatusFilter')?.value || '';
            try{
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">加载中...</td></tr>';
                const url = status === '' ? '/orders/all' : `/orders/all?status=${status}`;
                const res = await axios.get(url);
                if (!(res.data && res.data.code === 200)){
                    tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">加载失败</td></tr>';
                    return;
                }
                const list = res.data.data || [];
                if (!list.length){
                    tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">暂无订单</td></tr>';
                    return;
                }
                const badge = s => s===1? 'bg-success' : (s===2? 'bg-secondary' : 'bg-warning');
                const text = s => s===1? '已支付' : (s===2? '已退款' : '未支付');
                const srcText = t => t===1? '住院押金' : (t===2? '购药' : '-');
                tbody.innerHTML = list.map(o => {
                    const time = o.createTime ? new Date(o.createTime).toLocaleString() : '-';
                    const amt = (Number(o.amount)||0).toFixed(2);
                    const canRefund = o.payStatus === 1;
                    return `<tr>
                        <td>OD${o.orderId}</td>
                        <td>${o.pid}</td>
                        <td>${o.item}</td>
                        <td>${amt}</td>
                        <td><span class="badge ${badge(o.payStatus)}">${text(o.payStatus)}</span></td>
                        <td>${srcText(o.sourceType)}</td>
                        <td>${time}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-danger" ${canRefund? '' : 'disabled'} onclick="refundOrder(${o.orderId})">退款</button>
                        </td>
                    </tr>`;
                }).join('');
            } catch(e){
                console.error('加载订单失败', e);
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">加载失败</td></tr>';
            }
        }

        async function refundOrder(orderId){
            if(!confirm('确认对该订单执行退款吗？')) return;
            try{
                const res = await axios.post(`/orders/refund/${orderId}`);
                if (res.data && res.data.code === 200){
                    alert('退款成功');
                    loadAllOrders();
                } else {
                    alert('退款失败：' + (res.data?.msg || '未知错误'));
                }
            }catch(e){
                console.error('退款失败', e);
                alert('退款失败，请稍后重试');
            }
        }

        // 显示添加科室模态框
        function showAddDepartmentModal() {
            new bootstrap.Modal(document.getElementById('addDepartmentModal')).show();
        }

        // 显示添加医生模态框
        async function showAddDoctorModal() {
            // 加载科室选项
            await loadDepartmentOptions();
            new bootstrap.Modal(document.getElementById('addDoctorModal')).show();
        }

        // 加载科室选项
        async function loadDepartmentOptions() {
            try {
                const response = await axios.get('/department/query');
                if (response.data.code === 200) {
                    const departments = response.data.data || [];
                    const select = document.getElementById('docDepName');
                    select.innerHTML = '<option value="">请选择科室</option>';
                    
                    departments.forEach(dept => {
                        const option = document.createElement('option');
                        option.value = dept.depName;
                        option.textContent = dept.depName;
                        select.appendChild(option);
                    });
                }
            } catch (error) {
                console.error('加载科室选项失败:', error);
            }
        }

        // 加载编辑医生科室选项
        async function loadEditDoctorDepartmentOptions(currentDepId) {
            try {
                const response = await axios.get('/department/query');
                if (response.data.code === 200) {
                    const departments = response.data.data || [];
                    const select = document.getElementById('editDocDepName');
                    select.innerHTML = '<option value="">请选择科室</option>';
                    
                    departments.forEach(dept => {
                        const option = document.createElement('option');
                        option.value = dept.depName;
                        option.textContent = dept.depName;
                        if (dept.depId === currentDepId) {
                            option.selected = true;
                        }
                        select.appendChild(option);
                    });
                }
            } catch (error) {
                console.error('加载科室选项失败:', error);
            }
        }

        // 更新医生
        async function updateDoctor() {
            try {
                const form = document.getElementById('editDoctorForm');
                if (!form) {
                    alert('找不到编辑医生表单');
                    return;
                }
                
                const formData = new FormData(form);
                const data = Object.fromEntries(formData);
                
                // 验证必填字段
                const requiredFields = ['dId', 'name', 'sex', 'age', 'title', 'major', 'info', 'depName'];
                const missingFields = requiredFields.filter(field => !data[field] || data[field].trim() === '');
                
                if (missingFields.length > 0) {
                    alert(`请填写所有必填字段: ${missingFields.join(', ')}`);
                    return;
                }
                
                // 验证年龄
                const age = parseInt(data.age);
                if (isNaN(age) || age < 18 || age > 80) {
                    alert('年龄必须在18-80岁之间');
                    return;
                }
                
                // 转换数据类型
                data.dId = parseInt(data.dId);
                data.age = age;
                data.state = parseInt(data.state) || 1;
                
                // 显示加载状态
                const submitBtn = form.querySelector('button[onclick="updateDoctor()"]');
                const originalText = submitBtn.innerHTML;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>更新中...';
                submitBtn.disabled = true;
                
                const result = await apiCall('/doctor/update', 'PUT', data);
                
                if (result.success && result.data.code === 200) {
                    alert('医生信息更新成功！');
                    bootstrap.Modal.getInstance(document.getElementById('editDoctorModal')).hide();
                    await loadDoctors(); // 重新加载医生列表
                } else {
                    alert('更新失败：' + (result.error || result.data?.msg || '未知错误'));
                }
                
            } catch (error) {
                console.error('更新医生失败:', error);
                alert('更新失败，请检查网络连接');
            } finally {
                // 恢复按钮状态
                const submitBtn = form.querySelector('button[onclick="updateDoctor()"]');
                if (submitBtn) {
                    submitBtn.innerHTML = '更新';
                    submitBtn.disabled = false;
                }
            }
        }

        // 显示添加排班模态框
        async function showAddScheduleModal() {
            // 加载医生和科室选项
            await loadScheduleFormOptions();
            new bootstrap.Modal(document.getElementById('addScheduleModal')).show();
        }

        // 加载排班表单选项（医生和科室）
        async function loadScheduleFormOptions() {
            try {
                // 加载医生选项
                const doctorResult = await apiCall('/doctor/query');
                if (doctorResult.success) {
                    const doctors = doctorResult.data.data || [];
                    const doctorSelects = ['scheduleDId', 'editScheduleDId'];
                    
                    doctorSelects.forEach(selectId => {
                        const select = document.getElementById(selectId);
                        if (select) {
                            select.innerHTML = '<option value="">请选择医生</option>';
                            doctors.forEach(doctor => {
                                const option = document.createElement('option');
                                option.value = doctor.dId;
                                option.textContent = `${doctor.dName} (${doctor.depName})`;
                                select.appendChild(option);
                            });
                        }
                    });
                }
                
                // 加载科室选项
                const depResult = await apiCall('/department/query');
                if (depResult.success) {
                    const departments = depResult.data.data || [];
                    const depSelects = ['scheduleDepId', 'editScheduleDepId'];
                    
                    depSelects.forEach(selectId => {
                        const select = document.getElementById(selectId);
                        if (select) {
                            select.innerHTML = '<option value="">请选择科室</option>';
                            departments.forEach(dept => {
                                const option = document.createElement('option');
                                option.value = dept.depId;
                                option.textContent = dept.depName;
                                select.appendChild(option);
                            });
                        }
                    });
                }
            } catch (error) {
                console.error('加载排班表单选项失败:', error);
            }
        }

        // 添加科室
        async function addDepartment() {
            try {
                const form = document.getElementById('addDepartmentForm');
                const formData = new FormData(form);
                const data = Object.fromEntries(formData);
                
                const response = await axios.post('/department/add', data);
                if (response.data.code === 200) {
                    alert('科室添加成功！');
                    bootstrap.Modal.getInstance(document.getElementById('addDepartmentModal')).hide();
                    form.reset();
                    loadDepartments();
                } else {
                    alert('添加失败：' + response.data.msg);
                }
            } catch (error) {
                console.error('添加科室失败:', error);
                alert('添加失败，请检查网络连接');
            }
        }

        // 更新科室
        async function updateDepartment() {
            try {
                const form = document.getElementById('editDepartmentForm');
                const formData = new FormData(form);
                const data = Object.fromEntries(formData);
                
                const response = await axios.put('/department/update', data);
                if (response.data.code === 200) {
                    alert('科室更新成功！');
                    bootstrap.Modal.getInstance(document.getElementById('editDepartmentModal')).hide();
                    loadDepartments();
                } else {
                    alert('更新失败：' + response.data.msg);
                }
            } catch (error) {
                console.error('更新科室失败:', error);
                alert('更新失败，请检查网络连接');
            }
        }

        // 添加医生
        async function addDoctor() {
            try {
                const form = document.getElementById('addDoctorForm');
                if (!form) {
                    alert('找不到添加医生表单');
                    return;
                }
                
                const formData = new FormData(form);
                const data = Object.fromEntries(formData);
                
                // 验证必填字段
                const requiredFields = ['name', 'sex', 'age', 'title', 'major', 'info', 'depName', 'pw'];
                const missingFields = requiredFields.filter(field => !data[field] || data[field].trim() === '');
                
                if (missingFields.length > 0) {
                    alert(`请填写所有必填字段: ${missingFields.join(', ')}`);
                    return;
                }
                
                // 验证年龄
                const age = parseInt(data.age);
                if (isNaN(age) || age < 18 || age > 80) {
                    alert('年龄必须在18-80岁之间');
                    return;
                }
                
                // 转换数据类型
                data.age = age;
                data.state = 1;
                
                // 显示加载状态
                const submitBtn = form.querySelector('button[onclick="addDoctor()"]');
                const originalText = submitBtn.innerHTML;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>添加中...';
                submitBtn.disabled = true;
                
                const result = await apiCall('/doctor/signup', 'POST', data);
                
                if (result.success && result.data.code === 200) {
                    alert('医生添加成功！');
                    bootstrap.Modal.getInstance(document.getElementById('addDoctorModal')).hide();
                    form.reset();
                    await loadDoctors(); // 重新加载医生列表
                } else {
                    alert('添加失败：' + (result.error || result.data?.msg || '未知错误'));
                }
                
            } catch (error) {
                console.error('添加医生失败:', error);
                alert('添加失败，请检查网络连接');
            } finally {
                // 恢复按钮状态
                const submitBtn = form.querySelector('button[onclick="addDoctor()"]');
                if (submitBtn) {
                    submitBtn.innerHTML = '添加';
                    submitBtn.disabled = false;
                }
            }
        }

        // 删除排班
        async function deleteSchedule(sId) {
            try {
                if (!sId || sId <= 0) {
                    alert('无效的排班ID');
                    return;
                }
                
                // 确认删除
                if (!confirm('确定要删除这个排班吗？\n\n删除后将无法恢复！')) {
                    return;
                }
                
                // 显示加载状态
                const loadingMessage = document.createElement('div');
                loadingMessage.className = 'alert alert-info text-center';
                loadingMessage.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>正在删除排班...';
                
                // 在页面顶部显示加载状态
                const container = document.querySelector('.main-content');
                if (container) {
                    container.insertBefore(loadingMessage, container.firstChild);
                }
                
                const result = await apiCall(`/schedule/delete/${sId}`, 'DELETE');
                
                // 移除加载状态
                if (loadingMessage.parentNode) {
                    loadingMessage.parentNode.removeChild(loadingMessage);
                }
                
                if (result.success && result.data.code === 200) {
                    alert('排班删除成功！');
                    await loadSchedules(); // 重新加载排班列表
                } else {
                    alert('删除失败：' + (result.error || result.data?.msg || '未知错误'));
                }
                
            } catch (error) {
                console.error('删除排班失败:', error);
                alert('删除失败，请检查网络连接');
            }
        }

        // 编辑科室
        async function editDepartment(depId) {
            try {
                // 获取科室信息
                const response = await axios.get(`/department/Info/${depId}`);
                if (response.data.code === 200) {
                    const dept = response.data.data;
                    
                    // 填充编辑表单
                    document.getElementById('editDepId').value = dept.depId;
                    document.getElementById('editDepName').value = dept.depName;
                    document.getElementById('editDepInfo').value = dept.depInfo;
                    document.getElementById('editDepLevel').value = dept.depLevel;
                    document.getElementById('editDepPhone').value = dept.depPhone;
                    
                    // 显示编辑模态框
                    new bootstrap.Modal(document.getElementById('editDepartmentModal')).show();
                } else {
                    alert('获取科室信息失败：' + response.data.msg);
                }
            } catch (error) {
                console.error('获取科室信息失败:', error);
                alert('获取科室信息失败，请检查网络连接');
            }
        }

        // 删除科室
        async function deleteDepartment(depId) {
            if (confirm('确定要删除这个科室吗？')) {
                try {
                    const response = await axios.delete(`/department/delete/${depId}`);
                    if (response.data.code === 200) {
                        alert('删除成功！');
                        loadDepartments();
                    } else {
                        alert('删除失败：' + response.data.msg);
                    }
                } catch (error) {
                    console.error('删除科室失败:', error);
                    alert('删除失败，请检查网络连接');
                }
            }
        }

        // 编辑医生
        async function editDoctor(dId) {
            try {
                if (!dId || dId <= 0) {
                    alert('无效的医生ID');
                    return;
                }
                
                // 显示加载状态
                showLoadingState('editDoctorModal .modal-body', '正在加载医生信息...', 1);
                
                const result = await apiCall(`/doctor/info/${dId}`);
                
                if (!result.success) {
                    alert('获取医生信息失败：' + result.error);
                    return;
                }
                
                if (result.data.code !== 200) {
                    alert('获取医生信息失败：' + result.data.msg);
                    return;
                }
                
                const doctor = result.data.data;
                if (!doctor) {
                    alert('医生信息不存在');
                    return;
                }
                
                // 填充编辑表单
                const form = document.getElementById('editDoctorForm');
                if (!form) {
                    alert('找不到编辑医生表单');
                    return;
                }
                
                // 安全地设置表单值
                const setFormValue = (id, value) => {
                    const element = document.getElementById(id);
                    if (element) element.value = value || '';
                };
                
                setFormValue('editDocId', doctor.dId);
                setFormValue('editDocName', doctor.dName);
                setFormValue('editDocSex', doctor.dSex);
                setFormValue('editDocAge', doctor.dAge);
                setFormValue('editDocTitle', doctor.dTitle);
                setFormValue('editDocMajor', doctor.dMajor);
                setFormValue('editDocInfo', doctor.dInfo);
                setFormValue('editDocState', doctor.dState);
                
                // 加载科室选项并设置当前科室
                await loadEditDoctorDepartmentOptions(doctor.depId);
                
                // 显示编辑模态框
                new bootstrap.Modal(document.getElementById('editDoctorModal')).show();
                
            } catch (error) {
                console.error('编辑医生失败:', error);
                alert('编辑医生失败，请检查网络连接');
            }
        }

        // 删除医生
        async function deleteDoctor(dId) {
            try {
                if (!dId || dId <= 0) {
                    alert('无效的医生ID');
                    return;
                }
                
                // 确认删除
                if (!confirm('确定要删除这个医生吗？\n\n删除后将无法恢复，包括：\n- 医生基本信息\n- 医生登录账号\n- 相关排班记录\n\n请谨慎操作！')) {
                    return;
                }
                
                // 显示加载状态
                const loadingMessage = document.createElement('div');
                loadingMessage.className = 'alert alert-info text-center';
                loadingMessage.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>正在删除医生...';
                
                // 在页面顶部显示加载状态
                const container = document.querySelector('.main-content');
                if (container) {
                    container.insertBefore(loadingMessage, container.firstChild);
                }
                
                const result = await apiCall(`/doctor/delete/${dId}`, 'DELETE');
                
                // 移除加载状态
                if (loadingMessage.parentNode) {
                    loadingMessage.parentNode.removeChild(loadingMessage);
                }
                
                if (result.success && result.data.code === 200) {
                    alert('医生删除成功！');
                    await loadDoctors(); // 重新加载医生列表
                } else {
                    alert('删除失败：' + (result.error || result.data?.msg || '未知错误'));
                }
                
            } catch (error) {
                console.error('删除医生失败:', error);
                alert('删除失败，请检查网络连接');
            }
        }

        // 刷新医生数据
        async function refreshDoctorData() {
            console.log('手动刷新医生数据...');
            await loadDoctors();
        }

        // 导出医生数据（CSV格式）
        function exportDoctorData() {
            try {
                if (!allDoctors || allDoctors.length === 0) {
                    alert('没有医生数据可导出');
                    return;
                }
                
                const headers = ['姓名', '性别', '年龄', '职称', '专业', '所属科室', '状态'];
                const csvContent = [
                    headers.join(','),
                    ...allDoctors.map(doctor => [
                        doctor.dName || '',
                        doctor.dSex || '',
                        doctor.dAge || '',
                        doctor.dTitle || '',
                        doctor.dMajor || '',
                        doctor.depName || '',
                        doctor.dState === 1 ? '在职' : '离职'
                    ].join(','))
                ].join('\n');
                
                const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', `医生数据_${new Date().toISOString().split('T')[0]}.csv`);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                console.log('医生数据导出成功');
            } catch (error) {
                console.error('导出医生数据失败:', error);
                alert('导出失败，请重试');
            }
        }

        // 统计医生信息
        function getDoctorStatistics() {
            if (!allDoctors || allDoctors.length === 0) {
                return {
                    total: 0,
                    active: 0,
                    inactive: 0,
                    byDepartment: {}
                };
            }
            
            const stats = {
                total: allDoctors.length,
                active: allDoctors.filter(d => d.dState === 1).length,
                inactive: allDoctors.filter(d => d.dState === 0).length,
                byDepartment: {}
            };
            
            allDoctors.forEach(doctor => {
                const depName = doctor.depName || '未知科室';
                if (!stats.byDepartment[depName]) {
                    stats.byDepartment[depName] = 0;
                }
                stats.byDepartment[depName]++;
            });
            
            return stats;
        }

        // 显示医生统计信息
        function showDoctorStatistics() {
            const stats = getDoctorStatistics();
            const message = `
医生统计信息：
总人数：${stats.total}
在职：${stats.active}
离职：${stats.inactive}

各科室分布：
${Object.entries(stats.byDepartment)
    .map(([dep, count]) => `${dep}：${count}人`)
    .join('\n')}
            `;
            alert(message);
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('token');
                localStorage.removeItem('userInfo');
                window.location.href = '/login';
            }
        }

        async function updateSchedule() {
            try {
                const form = document.getElementById('editScheduleForm');
                if (!form) {
                    alert('找不到编辑排班表单');
                    return;
                }
                
                const formData = new FormData(form);
                const data = Object.fromEntries(formData);
                
                // 验证必填字段
                const requiredFields = ['sId', 'dId', 'DepId', 'date', 'time'];
                const missingFields = requiredFields.filter(field => !data[field] || data[field].trim() === '');
                
                if (missingFields.length > 0) {
                    alert(`请填写所有必填字段: ${missingFields.join(', ')}`);
                    return;
                }
                
                // 转换数据类型与日期格式
                data.sId = parseInt(data.sId);
                data.dId = parseInt(data.dId);
                data.DepId = parseInt(data.DepId);
                data.date = normalizeYMD(data.date);
                
                // 显示加载状态
                const submitBtn = form.querySelector('button[onclick="updateSchedule()"]');
                const originalText = submitBtn.innerHTML;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>更新中...';
                submitBtn.disabled = true;
                
                const result = await apiCall('/schedule/update', 'PUT', data);
                
                if (result.success && result.data.code === 200) {
                    alert('排班信息更新成功！');
                    bootstrap.Modal.getInstance(document.getElementById('editScheduleModal')).hide();
                    await loadSchedules(); // 重新加载排班列表
                } else {
                    alert('更新失败：' + (result.error || result.data?.msg || '未知错误'));
                }
                
            } catch (error) {
                console.error('更新排班失败:', error);
                alert('更新失败，请检查网络连接');
            } finally {
                // 恢复按钮状态
                const submitBtn = form.querySelector('button[onclick="updateSchedule()"]');
                if (submitBtn) {
                    submitBtn.innerHTML = '更新';
                    submitBtn.disabled = false;
                }
            }
            
        }
                // 购药审批模块
                function showDrugPurchaseApproval() {
            hideAllSections();
            document.getElementById('drugPurchaseApproval').style.display = 'block';
            updateActiveNav('drugPurchaseApproval');
            loadDrugPurchasePending();
        }

        async function loadDrugPurchasePending() {
            const tbody = document.getElementById('purchaseApprovalTable');
            if (!tbody) return;
            tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">加载中...</td></tr>';
            try {
                const [pendingRes, patientRes] = await Promise.all([
                    axios.get('/purchase/pending'),
                    axios.get('/patient/query').catch(_=>({data:{code:500,data:[]}}))
                ]);
                if (!(pendingRes.data && pendingRes.data.code === 200)) {
                    tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">加载失败</td></tr>';
                    return;
                }
                const patients = (patientRes.data && patientRes.data.code===200) ? (patientRes.data.data||[]) : [];
                const pMap = new Map();
                patients.forEach(p=>{ const id=p.pId||p.pid||p.id; if(id) pMap.set(Number(id), p); });

                const list = pendingRes.data.data || [];
                if (!list.length) {
                    tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">暂无待审批申请</td></tr>';
                    return;
                }
                tbody.innerHTML = list.map(x=>{
                    const pid = Number(x.pId||x.pid);
                    const p = pMap.get(pid)||{};
                    const pname = p.pName||p.pname||'-';
                    const time = x.applyTime ? new Date(x.applyTime).toLocaleString() : '-';
                    const total = (Number(x.totalAmount)||0).toFixed(2);
                    const items = Array.isArray(x.items)? x.items.map(it => `${it.drugName}x${it.quantity}`).join('，') : '';
                    return `
                        <tr>
                            <td>PU${x.purchaseId}</td>
                            <td>${pname}</td>
                            <td>${time}</td>
                            <td>${total}</td>
                            <td><button class="btn btn-sm btn-outline-primary" onclick="alert('${items.replace(/'/g, "\\'")}')">查看</button></td>
                            <td>
                                <button class="btn btn-sm btn-success me-1" onclick="approvePurchase(${x.purchaseId}, true)">通过</button>
                                <button class="btn btn-sm btn-danger" onclick="approvePurchase(${x.purchaseId}, false)">拒绝</button>
                            </td>
                        </tr>`;
                }).join('');
            } catch (e) {
                console.error('加载购药审批列表失败', e);
                tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">加载失败</td></tr>';
            }
        }

        async function approvePurchase(purchaseId, pass) {
            try {
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const approverId = 1;
                if (!approverId) { alert('无法获取医生ID'); return; }
                const body = { purchaseId, approverId, approverRole: 2, pass, remark: '' };
                const res = await axios.post('/purchase/approve', body);
                if (res.data && res.data.code === 200) {
                    alert('操作成功');
                    loadDrugPurchasePending();
                } else {
                    alert('操作失败：' + (res.data?.msg || '未知错误'));
                }
            } catch (e) {
                console.error('审批失败', e);
                alert('审批失败，请稍后重试');
            }
        }

        // 新增：购药审批全局方法
        window.showDrugPurchaseApproval = showDrugPurchaseApproval;
        window.loadDrugPurchasePending = loadDrugPurchasePending;
        window.approvePurchase = approvePurchase;
    </script>
</body>
</html>
